how to convert Integer values into timestamp format? - php

I have an Integer column "duration_temp" that have values represent the duration in minutes, I want to copy those values in another column "duration" of type timestamp, I'm having the problem of how to convert those Int minutes into timestamps format, for example:
if a value in Int is set to 4 then I should convert it to yyyy-mm-dd 00:04:00.
is there a function that can do that or close from doing that?any suggestion would be appreciate it.

If you have a duration in minutes. You could use DateInterval like this.
$yourDate = new DateTime('2021-01-01 00:00:00');
$durationInMinutes = 4;
$interval = new DateInterval("PT{$durationInMinutes}M");
$yourDate->add($interval);
echo $yourDate->format('Y-m-d H:i:s');
https://www.php.net/manual/en/dateinterval.construct.php

If you mean that you just have minutes and want to make a timestamp from it with current date information, try this (after adding use Carbon\Carbon; in top of you file):
$minutes = 4;
return Carbon::create(now()->year, now()->month, now()->day, 0, $minutes)->toDateTimeString();

As your integer column duration_temp is in minutes, you have to convert it to seconds before you can get the expected result.
Take your example :
Int = 4 minutes => Int = 4 * 60 = 240 second
To finish :
date ("Y-m-d H:i:s", 240); // will give you 1970-01-01 00:04:00

DateTime accepts extensive Relative Formats. This makes possible as an example:
$durationInMinutes = 67;
$date = date_create('2021-01-01 '.$durationInMinutes.' Minutes');
//or $date = new DateTime('2021-01-01 '.$durationInMinutes.' Minutes');
echo $date->format('Y-m-d H:i:s');
//2021-01-01 01:07:00
Also works correctly with negative minute numbers.

Related

getting only time timestamp from string

Suppose I have a time string '9:30' which I want to convert to timestamp.
What I do right now is extracting it and manually calculate the timestamp.
list($hour, $minute) = explode(':', '9:30');
$timestamp = $hour * 3600 + $minute * 60;
I'm wondering whether there is a smart way using Carbon or DateTime object.
use strtotime()
manual
$time = '9:30';
$timestamp = strtotime($time);
echo date('H:i',$timestamp);
I don't think you'll be able to get a timestamp from only hour or minute, as timestamp is number of seconds from 00:00:00 Thursday 1 January 1970 (check wikipedia link for more details). So without the date part you can't have a timestamp. Could you please explain how you're planning to use this?
If you're planning to calculate a different timestamp from a given datetime, then you can just do it differently. Say you're planning to get the timestamp 1 day or 24 hours after given time, then you can do it like this (non object oriented way):
$givenTimestamp = strtotime('17-06-2018 09:30:00');
$dayInSeconds = 24*60*60;
$calculatedTimeStamp = $givenTimestamp + $dayInSeconds;
If you're just trying to get how many seconds has been passed for the time section of the timestamp (like 9:30 in your example for a given day), then you can just do it like this:
list($hour, $minute) = explode(':', date ('H:i', strtotime('2018-06-16 09:30:00')));
$secondsSinceStartOfDay = intval($hour)*60*60 + intval($minute) * 60;
You may get the same result without using the intval on $hour and $minute, but it would be better to use intval on them to avoid possible issues in some cases.
Update with Carbon
From Carbon documentation, it seems like you still need the date part to generate the timestamp. So if you have your $date like this '2018-06-16' and $time like this '09:30', then you can recreate your datetime like this:
$dateTimeString = $date .' '. $time .':00';
$carbonDateTime = Carbon::parse($dateTimeString);
// $carbonDateTime will now have your date time reference
// you can now get the timestamp like this
echo $carbonDateTime->timestamp;

PHP| arrays with times

I need to compare bentween a time taken from a database to the current time.
$DBtime = "2013-10-29 17:38:55";
this is the format of the arrays in the database.
How can I compare it with the current time?
Im not sure how, but maybe converting DBtime to Unixtime then:
(CurrentUnixTime - dbUnixTime) = x
Or maybe, we can take the 17:38 and compare it somehow with date("G:i");
Thank you! I hope you understand what I mean.
You can transform it into a UNIX timestamp using strtotime and then subtract the current timestamp by it.
$DBtime = "2013-10-29 17:38:55";
$db_timestamp = strtotime($DBtime);
$now = time();
$difference = $now - $db_timestamp;
echo $difference;
This will give you the difference in seconds.
You can convert the DBtime string to a unix timestamp in PHP using strtotime. In MySQL, you can use UNIX_TIMESTAMP when querying the column.
time() - strtotime($DBtime)
$date1 = new DateTime('2013-10-29 17:38:55');
$date2 = new DateTime('2013-11-29 18:28:21');
$diff = $date1->diff($date2);
echo $diff->format('%m month, %d days, %h hours, %i minutes');
$DBtime = "2013-10-29 17:38:55";
// Set whatever timezone was used to save the data originally
date_default_timezone_set('CST6CDT');
// Get the current date/time and format the same as your input date
$curdate=date("Y-m-d H:i:s", time());
if($DBtime == $curdate) {
// They match, do something
} else {
// They don't match
}

How to increase the value of a unix timestamp stored in a variable by X hours?

I have a php function that creates a unix timestamp and stores it in a variable. Let's call that variable $timestamp. I'm looking for a function that will allow return two new variables that are a each a different number of hours later than the original timestamp. Is there a way to do this?
This will return a date 3 and 7 days after the supplied date as a unix timestamp. You can edit the math to get the times you need.
$timestamp = date('U');
var_dump(get_more_dates($timestamp));
function get_more_dates($timestamp){
// 60 seconds * 60 minutes * 24 hours * 3 days
$new_date_1 = (60*60*24*3)+timestamp;
$new_date_2 = (60*60*24*7)+timestamp;
return array( $new_date_1, $new_date_1 );
}
Try this-
date( "Y-M-d H:i:s", strtotime( $timestamp ) + $hours * 3600 );
strtotime to convert the timestamp string to timestamp value;
then adding the no. of seconds (hours*36*36); then converting back to the timestamp format using date()
So, you can simply add this code to a function, and give any desired values of $hours; to get the-
different number of hours later than the original timestamp

In an LDAP 'lastlogon' lookup how do I decipher the result?

I'm using a PHP script to grab data from Active Directory using LDAP..
When I get the user values for 'lastlogon' I get a number like 129937382382715990
I've tried to figure out how to get the date/time from this but have no idea, can anybody help?
Read this comment on the PHP: LDAP Functions page.
All of them are using "Interval" date/time format with a value that represents the number of 100-nanosecond intervals since January 1, 1601 (UTC, and a value of 0 or 0x7FFFFFFFFFFFFFFF, 9223372036854775807, indicates that the account never expires): https://msdn.microsoft.com/en-us/library/ms675098(v=vs.85).aspx
So if you need to translate it from/to UNIX timestamp you can easily calculate the difference with:
<?php
$datetime1 = new DateTime('1601-01-01');
$datetime2 = new DateTime('1970-01-01');
$interval = $datetime1->diff($datetime2);
echo ($interval->days * 24 * 60 * 60) . " seconds\n";
?>
The difference between both dates is 11644473600 seconds. Don't rely on floating point calculations nor other numbers that probably were calculated badly (including time zone or something similar).
Now you can convert from LDAP field:
<?php
$lastlogon = $info[$i]['lastlogon'][0];
// divide by 10.000.000 to get seconds from 100-nanosecond intervals
$winInterval = round($lastlogon / 10000000);
// substract seconds from 1601-01-01 -> 1970-01-01
$unixTimestamp = ($winInterval - 11644473600);
// show date/time in local time zone
echo date("Y-m-d H:i:s", $unixTimestamp) ."\n";
?>
This is the number 100-nanosecond ticks since 1 January 1601 00:00:00 UT.
System time article in Wikipedia can give you more details.
What about this:
$timeStamp = 129937382382715990;
echo date('Y-m-d H:i:s', $timeStamp);
EDIT ------
I just tried the following and noticed that this method wont work unless the clock on your machine is set 10 years in the future. Below is the code I used to prove the above pretty much useless unless you do more processing maybe..
$time = time();
echo date('Y-m-d H:i:s', $time);
echo "<br />";
$timeStamp = 129937382382715990;
echo date('Y-m-d H:i:s', $timeStamp);
In my case I'm using Pentaho. With a Modified Javascript value you can convert the values, lastLogon is the column I wanna convert from data stream:
calendar = java.util.Calendar.getInstance();
calendar.setTime(new Date("1/1/1601"));
base_1601_time = calendar.getTimeInMillis();
calendar.setTime(new Date("1/1/1970"));
base_1970_time = calendar.getTimeInMillis();
ms_offset = base_1970_time - base_1601_time;
calendar.setTimeInMillis( lastLogon / 10000 - ms_offset); //lastLogon is a column from stream
var converted_AD_time = calendar.getTime(); // now just add this variable 'converted_AD_time' to the 'Fields' as a show in the image below

How to get millisecond between two dateTime obj?

How to get millisecond between two DateTime objects?
$date = new DateTime();
$date2 = new DateTime("1990-08-07 08:44");
I tried to follow the comment below, but I got an error.
$stime = new DateTime($startTime->format("d-m-Y H:i:s"));
$etime = new DateTime($endTime->format("d-m-Y H:i:s"));
$millisec = $etime->getTimestamp() - $stime->getTimestamp();`
I get the error
Call to undefined method DateTime::getTimestamp()
In the strict sense, you can't.
It's because the smallest unit of time for the DateTime class is a second.
If you need a measurement containing milliseconds then use microtime()
Edit:
On the other hand if you simply want to get the interval in milliseconds between two ISO-8601 datetimes then one possible solution would be
function millisecsBetween($dateOne, $dateTwo, $abs = true) {
$func = $abs ? 'abs' : 'intval';
return $func(strtotime($dateOne) - strtotime($dateTwo)) * 1000;
}
Beware that by default the above function returns absolute difference. If you want to know whether the first date is earlier or not then set the third argument to false.
// Outputs 60000
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31");
// Outputs -60000 indicating that the first argument is an earlier date
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31", false);
On systems where the size of time datatype is 32 bits, such as Windows7 or earlier, millisecsBetween is only good for dates between 1970-01-01 00:00:00 and 2038-01-19 03:14:07 (see Year 2038 problem).
Sorry to digg out an old question, but I've found a way to get the milliseconds timestamp out of a DateTime object:
function dateTimeToMilliseconds(\DateTime $dateTime)
{
$secs = $dateTime->getTimestamp(); // Gets the seconds
$millisecs = $secs*1000; // Converted to milliseconds
$millisecs += $dateTime->format("u")/1000; // Microseconds converted to seconds
return $millisecs;
}
It requires however that your DateTime object contains the microseconds (u in the format):
$date_str = "20:46:00.588";
$date = DateTime::createFromFormat("H:i:s.u", $date_str);
This is working only since PHP 5.2 hence the microseconds support to DateTime has been added then.
With this function, your code would become the following :
$date_str = "1990-08-07 20:46:00.588";
$date1 = DateTime::createFromFormat("Y-m-d H:i:s.u", $date_str);
$msNow = (int)microtime(true)*1000;
echo $msNow - dateTimeToMilliseconds($date1);
DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the 'u' format string.
<?php
// Instantiate a DateTime with microseconds.
$d = new DateTime('2011-01-01T15:03:01.012345Z');
// Output the microseconds.
echo $d->format('u'); // 012345
// Output the date with microseconds.
echo $d->format('Y-m-d\TH:i:s.u'); // 2011-01-01T15:03:01.012345
// Unix Format
echo "<br>d2: ". $d->format('U.u');
function get_data_unix_ms($data){
$d = new DateTime($data);
$new_data = $d->format('U.u');
return $new_data;
}
function get_date_diff_ms($date1, $date2)
{
$d1 = new DateTime($date1);
$new_d1 = $d1->format('U.u');
$d2 = new DateTime($date2);
$new_d2 = $d2->format('U.u');
$diff = abs($new_d1 - $new_d2);
return $diff;
}
https://www.php.net/manual/en/class.datetime.php
Here's a function to do that + tests.
https://gist.github.com/vudaltsov/0bb623b9e2817d6ce359eb88cfbf229d
DateTime dates are only stored as whole seconds. If you still need the number of milliseconds between two DateTime dates, then you can use getTimestamp() to get each time in seconds (then get the difference and turn it into milliseconds):
$seconds_diff = $date2.getTimestamp() - $date.getTimestamp()
$milliseconds_diff = $seconds_diff * 1000

Categories