Date is different when converted - php

hello i am working with the Date() function i am getting a time that is current and time that is coming from a database to compare the times, but the dates are different:
date_default_timezone_set("America/Los_Angeles"); // set time zone to LA
$date = date("m-d-Y h:i:s"); // current time
$current_time = strtotime($date); // current time in seconds
$get_time = 1357487529; //linux time from the server
$difference = $current_time - $get_time; //seconds that have pass already
$get_date = date("m-d-Y h:i:s", $get_time); // convert the linux time to current time and date
$exploded_get_date = explode(" ", $get_date); //divide the get date into 2 parts by space 0 = date 1 = time
$exploded_current_date = explode(" ", $date); //divide the current date into 2 parts by space 0 = date 1 = time
the results i get are:
01-Sun-2013 07:52:09 //get date
06-01-2013 07:56:25 //current date
1357487785 // current time
1357487529 // get time
256 //difference
why is it saying i have month 1 in the get date, but in the current date is actually month 6 and also the day it says it is Sunday 6, when is Saturday 1? how can i fix this?

m-d-Y is NOT a valid format for parsing. Only you Americans think it's sensible to put the elements in an unsorted order...
Anyway, the point is, what does 06-01-2013 mean? Is it June 1st, or January 6th?
For consistency's sake, the computer assumes January 6th (d-m-Y format).
I would strongly recommend using the Y-m-d H:i:s format, as this is inherently sortable as string due to being fully big-endian.
EDIT: It should be noted that you can just use time() to get the current timestamp.

Your code is VERY redundant:
$date = date("m-d-Y h:i:s"); // current time
$current_time = strtotime($date); // current time in seconds
can be replaced with a simple
$current_time = time();
and
$get_date = date("m-d-Y h:i:s", $get_time); // convert the linux time to current time and date
$exploded_get_date = explode(" ", $get_date); //divide the get date into 2 parts by space 0 = date 1 = time
$exploded_current_date = explode(" ", $date);
could just be
$exploded_date = date('m-d-y', $get_time);
$exploded_time = date('h:i:s', $get_time);
You are wasting a considerable amount of CPU cycles on useless/repetitive and ultimately redundant operations.
And in the greater picture, your error is that PHP's normal and easiest analysed/parsed date/time strings are in yyyy-mm-dd format. You're building mm-dd-yyyy, which is pretty much entirely scrambled. PHP cannot guess properly when you feed it uncertain formats. That means strtotime() is going to screw up and give you incorrect results.

Related

How to get next time occurrence from now, submitted in php?

I have an input file with type time. what I want to do is to get time from the moment now that is if time right now is 2019-11-26 23:50:00 and the value of input field if 22:30:00, I should get a date 2019-11-27 22:30:00.
How can achieve this in PHP? in short, get the datetime stamp for the next occurrence of 22:30:00 which is 2019-11-27 22:30:00 as per the given example.
answer found but can we optimize the code more ?
$a = explode(':', date('H:i:s', strtotime($validateData['time'])));
$str = '+'.$a[0].' hours '.$a[1].' minutes '.$a[2].' seconds';
$trigger_at = date(date('Y-m-d H:i:s', strtotime( $str, strtotime($validateData['date']))));
return $trigger_at;
This is simpler and a lot more readable
$time = "21:30:00"; // Time from input
$today = date("Y-m-d $time");
$tomorrow = date("Y-m-d H:i:s", strtotime($today)+86400);
$date = strtotime($today) < strtotime("now") ? $tomorrow : $today;
Explanation: We take timestamp at specified hour for today and tomorrow, if today timestamp has been passed, we use tomorrow timestamp. Simple. :)
All you are doing is appending (concatenating) a string onto another string.
$time = "22:30:00"; // This is the time you have
$date = date("Y-m-d"); // Right now in yyyy-mm-dd format.
$newdatetime = $date.' '.$time;
That will give you the current date with the supplied time appended to it. You can convert that back into a timestamp using:
$timestamp = strtotime($newdatetime);
The answer below is based on the original question in which the time was assumed to be an offset from now. It is left here simply to avoid deleting a lot of code.
The function strtotime is easy to use for that. However, it doesn't accept HH:MM:SS format. So, you have to alter the string. I would do it like:
$time = "22:30:00"; // This is the time you have
$a = explode(':', $time);
$str = '+'.$a[0].' hours '.$a[1].' minutes '.$a[2].' seconds'; // This breaks it into separate numbers with labels.
$date = date("Y-m-d h:i:s", strtotime($str)); // The adjusted date
You can change the format of the output as you like by changing the first string used in the date function.

Get seconds from a date to end of month PHP

Pulling a date of subscription from an sql database table we want the customer to have until the end of the month one year later to make a payment. The subscription is just some date within a month. The one year later part is easy, figuring out where the end of that month is and adding it, in seconds, to the one year part is giving me problems.
The date is stored as the number of seconds from unix ground zero. How do I find the number of seconds from that value to the end of that month? I've tried converting the date value to an actual date using m-i-Y
End of Month:
$expDate = date('m-i-Y',$row1["renewDate"]);
This works. I get the last day of that month in string form. But if I try:
$endOfMonth = strtotime($expDate);
Doesn't work....
echo'ing $expDate shows the last day of the month in string form.
echo'ing $endOfMonth returns nothing...
Thanks for any thoughts on this.
strtotime doesn't work properly with arbitrary date formats. You have two options:
Use date_create_from_format to parse custom date formats.
Convert your string to Y-m-d format which strtotime understands
automatically.
For example:
$date = date('Y-m-t', $row1["renewDate"]);
$timestamp = strtotime($date);
P.S. As mentioned in comments, you should use t instead of i.
You can play around with something like this. If the database has Epoch time then you can use the '#' symbol to convert it to a date. You can get the subscription date that way, and also the end of the subscription month date using m/t/Y. You can convert that back to DT and then to UNIX time with get Timestamp. Looks like it works for time = 1560961801.
$row1["renewDate"] = 1560961801;
$unixfromDB = $row1["renewDate"];
$date = new DateTime('#' .$unixfromDB); // your UNIX timestamp.
$subdate = $date->format( 'm/d/Y' ); // subscription date
$endmonth = $date->format( 'm/t/Y' ); // end of month date
$endmonth = DateTime::createFromFormat('m/d/Y', $endmonth);
$endmonth = $endmonth->getTimestamp(); // UNIX timestamp for end of month.
echo ($endmonth - $unixfromDB) / (60 * 60 *24); // days to end of month
Try using mktime() instead of strtotime().
<?
/* establish variables */
$now=time(); // epoch seconds right now
$expDate = date('m-t-Y', $row1["renewDate"]); //note the switch to 't' as suggested by #ehymel
$eom = mktime($expDate); // converts 'end of month' date into epoch seconds
/* results */
$secondsleft = $eom - $now; // number of seconds until the end of the month
echo $secondsleft; // return results
?>
mktime($expDate) unfortunately didn't work, at least with CentOS6.9. Even with the expdate variable it still returned current system time.
Using the date format that strtotime would recognize, Y-m-t, did work correctly. Thanks user1597430...

How do I convert date of format like /Date(1490914800000+0100)/ to mysql datetime format in php?

I have tried to solve it by extracting the numeric part and then parsed it using date function. But it shows me some old date which I guess is not correct.
$datef = "1490914800000+0100";
$adada = date('Y-m-d H:i:s', $datef);
// Gives date 1987-10-13 18:31:28 which is an old date. Please suggest.
One approach, well-covered by this SO question, is to use the DateTime() function to convert time in seconds since epoch to a date, and then display this date using format(). But there are two caveats with your data. First, you appear to have milliseconds since the epoch, which needs to be converted to seconds. Second, you also have a timezone shift, in hours, tagged to the end. I split your $datef string into two parts, epoch and timezone, then arrive at the number of seconds since epoch.
list($epoch, $timezone) = explode('+', $datef);
$epoch = ($epoch / 1000) + (substr($timezone, 0, 2)*60*60) +
(substr($timezone, 2, 2)*60);
$dt = new DateTime("#$epoch");
echo $dt->format('Y-m-d H:i:s');
Output:
2017-03-31 00:00:00
Demo here:
PHP Sandbox
The time seems to be in milliseconds.
You can add the timezone shift to the seconds. 1 hour = 3600 seconds.
$milliSeconds = intval("1490914800000");
$seconds = $milliSeconds/1000;
$date = date("Y-m-d H:i:s", $seconds);

Difference between timestamps in minutes in PHP

I want to get difference between 2 timestamps of format Y-m-d H:i:s in minutes in PHP.
The code used is,
$currentDate = date('Y-m-d H:i:s');
$userLastActivity = date($date);
$timeLapse = (($currentDate - $userLastActivity)/60);
Here, $date is obtained from database.
The value of $timeLapse is 0 in output. Please help.
Try using unix timestamp. Practically it measures the time in seconds from 1/1/1970 and it's a lot easier to use and understand than a php object.
$currentTimestamp = new DateTime()->getTimestamp();
$userLastActivity = date($date)->getTimestamp();
$timeLapse = (($currentDate - $userLastActivity)/60);
You should have the time saved as timestamp on the server too, in that case you could use the $date directly as a number, with no need for a conversion. And also, because it's universal, you can pass it around to javascript or any other language without any worries for conversion
Use strtotime to parse textual datetime into a Unix timestamp and substract $userLastActivity from $currentDate and divide by 60.
See if this helps -
<?php
$currentDate = strtotime(date('Y-m-d H:i:s'));
$date = "2016-10-11 02:40:50";
$userLastActivity = strtotime($date);
echo round(abs($currentDate - $userLastActivity) / 60). " minutes";
?>
For more details :strtotime
Change these 2 lines for a start, as I don't think dividing dates by 60 is gonna work to well.
$currentDate = time();
$userLastActivity = strtotime($date);
That way you have time stamps and not dates (string)

There is a simple way to get unix time range of a day if given a random timestamp from that day?

There is a simple way to get unix time range of a day if given a random timestamp from that day ?
I have a date like 1345547471 which is "Tue, 21 Aug 2012 11:11:11 GMT"
There is a php function that can receive a timestamp like this and return a 00:00 hours timestamp and a 23:59 hours timestamp of that day ?
Thank you.
Sure, DateTime can do that:
$time = 1345547471;
$date = new DateTime;
// $date->setTimezone( new DateTimeZone( "America/New_York")); // Can set TZ here if needed
$date->setTimestamp( $time);
Now, you can set the time to whatever you want:
$date->setTime( 0, 0, 0); // 0h 0m 0s
And grab the resulting UNIX Timestamp:
$timestamp = $date->getTimestamp();
Same thing for the next use-case:
$date->setTime( 23, 59, 0);
$timestamp = $date->getTimestamp();
It is important to note that DateTime will properly handle cases of daylight savings time and local time discontinuities.
You can use the mod (gives the remainder after a division) PHP function like this to get the first second of a Unix timestamp (ie, today 0:00:00)
$var=time()-(time()%86400);
Then with this unix timstamp, you can add 86399 to get the last second of the day.
Edit: This doesn't account for dalylight savings.
$ts = 1345547471;
$ts_00_00 = mktime(0,0,0, date("m", $ts), date("d",$ts), date("Y",$ts);
$ts_23_59 = mktime(23,59,59, date("m", $ts), date("d",$ts), date("Y",$ts);
Documentation:
http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.mktime.php
If you are using PHP >= 5.3.0 Then you can use this...
Check out for this.
http://www.php.net/manual/en/datetime.createfromformat.php
This is similar to Fluffeh's answer, but accounts for daylight savings time. This is based on the server's time zone.
//Get time range for today
$start = strtotime(date("Y-m-d")." 00:00:00");
$end = strtotime(date("Y-m-d")." 23:59:59");
//Show our date in a human-readable format for troubleshooting
echo date(DATE_RFC1036,$start)."<br>".date(DATE_RFC1036,$end);
If you want to specify a custom timezone instead of the server timezine, you can add it to like so:
//Get time range for today
$start = strtotime(date("Y-m-d")." 00:00:00 -0500");
$end = strtotime(date("Y-m-d")." 23:59:59 -0500");
//Show our date in a human-readable format for troubleshooting
echo date(DATE_RFC1036,$start)."<br>".date(DATE_RFC1036,$end);
Link to working Sample

Categories