Time comparison in php [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
strtotime date weird result
I am trying to compare two times for an attendance system, i am trying to get the accurate time for Arkansas,USA but im not being to able to get the correct time. Please, guide me in the right direction if i am doing something wrong, part of my code:
$curTime =DATE("H:i A", strtotime('GMT-6'));
foreach($res as $r)
{
$crs_id =$r['course_id'];
$query1 = "select * from tbl_course_time where course_id='$crs_id'";
$res1 = $obj->querySelect($query1);
$start_time = DATE("H:i", STRTOTIME($res1[0]['start_time']));
$end_time = DATE("H:i", STRTOTIME($res1[0]['end_time']));
if ($curTime > $start_time && $curTime < $end_time)
{
$qry="insert into tbl_attendance set stud_id='$id',attd_date='$curDateForDB',attd_time='$curTimeForDB',course_id='$attd_courseId'";
$res=$obj->queryInsert($qry);
$result1 = "taken";
}
}
It's giving me incorrect time's is it the GMT time im getting wrong or something else
Any help would be greatly appreciated, Thank you

Don't use strtotime('GMT-6') because GMT-6 is not a time; it's a time zone.
// gets the UTC time using gmdate() instead of date()
$utc_str = gmdate("M d Y H:i:s", time());
// get the UTC timestamp, should you need it
$utc = strtotime($utc_str);
If you're in PHP 5, the DateTime class is a very clean way to get times and also deal with time zone conversions.
Also, I encourage you to set your database up using UTC time, and convert the output to the user's time zone.

You're doing the gmt-6 business wrong. The following is on a server that's in GMT-6 already:
echo date('r'); // Thu, 13 Dec 2012 02:40:00 -0600
echo date('r', strtotime('gmt-6')); // Thu, 13 Dec 2012 08:40:17 -0600
Note the 6 hour difference (and 17 seconds while I was typing up the strtotime bits). Doing the gmt-6 bit in strtotime forces PHP to apply a 6 hour difference to a string that's already in some timezone already.

Related

Can date() be compared like this? [duplicate]

This question already has answers here:
Trying to define my own time type in PHP
(2 answers)
Closed 6 years ago.
I have had some issues with comparing date/times.
I had a working code that just stopped working all of a sudden. Now I made some changes to it and by some reason UNIX time is not correct.
Utime and nexttime is just an example string now, but in the code Utime is last time updated, and nexttime is next time a update will happen calculated from Utime.
Example:
$Utime = "201603300450"; // YmdHi 2016 03 30 04:50
$nexttime = "201603300520";
if (date("YmdHi")>=$Utime && date("YmdHi")>=$nexttime)
Is this a safe way to compare the timevalue? I had some issues with strtotime thats why I ask.
You should convert your dates to DateTime objects:
<?php
$Utime = "201603300450";
$nexttime = "201603300520";
$dateUtime = DateTime::createFromFormat('YmdHi', $Utime);
$datenexttime = DateTime::createFromFormat('YmdHi', $nexttime);
$nowDate = DateTime::createFromFormat('YmdHi', date('YmdHi'));
if ($nowDate>=$dateUtime && $nowDate>=$datenexttime)
//do your stuff...
Strtotime should work just fine, but you should stick to a valid format. "Y-m-d H:i:s" is a valid format for strtotime.
Hope it helps :)
strtotime() is a great helper in this regard.
Check out strtotime
$Utime = "201603300450";
$nexttime = "201603300520";
if ( strtotime('now') >= strtotime($Utime) && strtotime('now') >= strtotime($nexttime) )

Server Time - driving me nuts :-)

Okay so I have a server in Denver with a user in New Zealand. I know everything about the user (timezone etc) and through the program they request something to happen in advance - let's say at 11:30am on August 5th 2013. I have a CRON job that runs every 15 minutes and asks the database if any requests are pending for the next 15 minute period, but how do I convert their stored time to the servers equivalent.
I set the default timezone for calculations: date_default_timezone_set('America/Denver')
I take the time now on the server and turn it into epoch: strtotime(date('Y-m-d H:i:s'))
I add the 15 minutes to create a range: $forward15 = strtotime('now +15 minutes')
I get the user chosen date from the database (and their timezone): 2013-08-05 11:30:00
Now what? If I convert that into epoch, it'll just be the servers version of that date.
NEW SOLUTION SEE BELOW!
If you know the timezone you can simply "add" it to your time.
For example:
server time: 01/01/01 00:00
the time the user wants: 01/01/01 01:00
the timezone of the user: GMT - 5
Just get the time (01/01/01 01:00) and add +5 => 01/01/01 06:00
So: your script needs to be executed at 01/01/01 06:00
(convert to timestamp where needed)
Added a little php to demonstrate
<?php
$servertime = time(); //timestamp of 01/01/01 00:00
$usertime = "01/01/01 06:00";//database
$userUTC = "-5";//database
strreplace($userUTC, "-", "+";
$replacetext = $userUTC . " days";
$usertime = strtotime($replacetext, $usertime);//now usertime is in your local timezone
$crontime = date("d/m/Y H:i");//the time you want the script to be executed
?>
I'm just assuming that the timezone is saved as "-5" for example and not Europe/Amsterdam Just tell me if i'm wrong.
edit 14:37
This could be a even better solution i think!
<?php
$usertime = "01/01/01 06:00";
$userUTC = "-5";
$userdate = $usertime . " " . $userUTC;
$usertimestamp = strtotime($userdate);//now you have the timestamp with correct timezone
$crontime = date("d/m/Y H:i", $usertimestamp);//formatted to the right date
echo $crontime;
?>
Edit: 25-07-2013 14:26
New solution to suit your database:
<?php
$usertime = "01/01/01 06:00";
$userUTC = "Pacific/Auckland";//get from database
$userdate = $usertime . " " . $userUTC;
$usertimestamp = strtotime($userdate);//now you have the timestamp with correct timezone
$crontime = date("d/m/Y H:i", $usertimestamp);//formatted to the right date
echo $crontime;
?>
the server is in which GMT time zone here is extremely easy way to get time and date for any time zone. This is done with time() and gmdate() function. gmdate() function normally give us GMT time but by doing a trick with time() function we can get GMT+N or GMT-N means we can get time for any GMT time zone.
For example you have to get time for GMT+5 we will do it like following
<?php
$offset=5*60*60; //converting 5 hours to seconds.
$dateFormat="d-m-Y H:i";
$timeNdate=gmdate($dateFormat, time()+$offset);
?>
Now if you have to get the time which is GMT-5 now we will just subtract the offset from the time() instead of adding into time like in following example we are getting time for GMT-4
<?php
$offset=4*60*60; //converting 5 hours to seconds.
$dateFormat="d-m-Y H:i";
$timeNdate=gmdate($dateFormat, time()-$offset);
?>

how to convert timestamp to date in codeigniter

I want to convert 1373892900000 to Monday 2013/07/15 8:55 AM in Codeigniter.
However, I keep receiving a totally different result by converting the timestamp using the function i have written, please note:I need to change the dates according to different timezones, that is why I want to write it this way:
public function time_convert($timestamp){
$this->load->helper('date');
date_default_timezone_set('UTC');
$daylight_saving = TRUE;
$timezone = "UM4"; //toronto or new york timezone
$time = gmt_to_local($timestamp, $timezone, $daylight_saving);
$final_time = standard_date('DATE_RFC822', $time);
return $final_time;
}
Result from the above function is: Sat, 08 Dec 06 01:40:00 +0000
And if I don't put date_default_timezone_set('UTC'); in the above function, I get this date instead Sat, 08 Dec 06 02:40:00 +0100. My codeigniter seems to default the timezone to Europe/Berlin.
Can anyone please help me correct any of the mistakes I might have made?
Why not just use PHP's date function?
public function time_convert($timestamp){
return date('l Y/m/d H:i', $timestamp);
}
For different timezones use a DateTime object:
public function time_convert($timestamp, $timezone = 'UTC'){
$datetime = new DateTime($timestamp, new DateTimeZone($timezone));
return $datetime->format('l Y/m/d H:i');
}
Think that should work. Note: I tihnk you need at least PHP version 5.20 for the TimeZone class.
<?php
$time_str=1373892900000;
echo gmdate("fill with your format", $time_str);
?>
your format = format your time in php, reading this page for details.
http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.gmdate.php
Appears as though an invocation of standard_date with the DATE_ATOM format may sort you:
echo unix_to_human(time(), true, 'us'); # returns 2013-07-12 08:01:02 AM, for example
There are a whole host of other options for the format, enumerated on the linked page.
This how to covert timestamp to date very simple:
echo date('m/d/Y', 1299446702);
to convert timestamp to human readable format try this:
function unix_timestamp_to_human ($timestamp = "", $format = 'D d M Y - H:i:s')
{
if (empty($timestamp) || ! is_numeric($timestamp)) $timestamp = time();
return ($timestamp) ? date($format, $timestamp) : date($format, $timestamp);
}
$unix_time = "1251208071";
echo unix_timestamp_to_human($unix_time); //Return: Tue 25 Aug 2009 - 14:47:51
if you want to convert it to a format like this: 2008-07-17T09:24:17Z than use this method
<?php
$timestamp=1333699439;
echo gmdate("Y-m-d\TH:i:s\Z", $timestamp);
?>
for details about date:
http://php.net/manual/en/function.date.php
Your timestamp is coming from javascript on the client, I would guess, because it appears to be in milliseconds. php timestamps are in seconds. So to get the answer you want, first divide by 1000.
Showing the full year would have made the issue more obvious, as you would have seen the year as 45,506.

How to convert datetime to GMT in php

Alright, so i'm not sure if im converting user input time to GMT properly. I will be having users across several timezones entering "events" and they will have to be able to see "how long untill" or "how long since" the current time();
This is how I was planning to convert the time they input. It will start as something like 07/21/2011 01:30 am Then,
echo gmdate('Y-m-d H:i:s',strtotime('07/21/2011 01:30 am'));
gives me 2011-07-21 08:30:00
So I was planning to take the value of gmdate('Y-m-d H:i:s',strtotime('07/21/2011 01:30 am')); then take time() and display "how long until this event" to users. But it seems like there is always 10 hours added onto the result, so if if i was scheduling an event 30 min from now it would say 10 hours 30 min from now. So, im thinking im not converting the local time correctly or something.
What am I missing? Maybe I just dont properly understand GMT. How can I make sure all the times involved are GMT so all times are universal to all the users on the website?
Other info if it helps:
The server timezone is America/Los_Angeles
EDIT:
After everyones suggestions i've tried setting this at the top of my php code:
date_default_timezone_set("GMT");
and I tried using date('Y-m-d H:i:s') to do the comparison to figure out the diff, but its saying "3 hours ago" rather than the 10 hours from now. So this definately changed things.
But still not correct.
I've confirmed date('Y-m-d H:i:s') is returning the correct and current GMT. So thats good.
But the user input date is off. How am I converting it incorrectly?
EDIT AGAIN(including some test results after Salman A's suggestions):
2:55am - my current local time EST
date('Y-m-d H:i:s') shows up as 2011-07-21 06:56:43 - which is correct
3:00am EST is the time in the future I submitted as 07/21/2011 03:00 am
Here's how I get the time "convert it" and submit it to my DB:
$time = $_POST['time'];
//there is where im assuming it turns my EST time to the GMT equivalent.
$the_date = strtotime($time . ' GMT');
$utctime = gmdate('Y-m-d H:i:s',$the_date);
I'm expecting my function to tell me the event is 5 minutes from now, but its hours off.
just to make sure the user submitted time was actually converted to GMT i display $utctime and it shows up as 2011-07-21 03:00:00 - which is not 08:00 or 07:00 (which i think one of those would be the GMT equivalent)
So how do I convert it?
So, what im seeing is strtotime($time . ' GMT'); doesn't seem to be applying the GMT to the local time I supply. On a side note: somone suggested I have date_default_timezone_set("GMT"); in my code, so i have it at the top. Should I remove it? but i noticed if i remove it the GMT is incorrect. So thats why I left it.
If you simply need to calculate the difference between two time values:
<?php
$time = '07/21/2011 11:30 am';
$timeleft = strtotime($time) - time();
// target time....: 2011-07-21 11:30:00
// current time...: 2011-07-21 11:13:45
// difference.....: 975 seconds (16 min, 15 seconds)
The above example assumes that $time has same timezone as that used by the time() function i.e. the server's timezone.
If the timezones differ, you must normalize them in order for subtraction to work as expected. So for example if you're storing GMT date/time in your database then the above example becomes:
<?php
$time = '07/21/2011 06:30 am';
$timeleft = strtotime($time . ' GMT') - time();
// target time............: 2011-07-21 06:30:00 GMT
// converted local time...: 2011-07-21 11:30:00 PKT
// current time...........: 2011-07-21 11:34:48 PKT
// difference.............: -288 seconds (minus 4 minutes, 48 seconds)
Edit 1
Regarding this code:
$time = $_POST['time'];
If your users are from various parts of the world, you should either:
ask them to enter the date/time in GMT
ask them to enter a timezone for the date entered
You can later convert the date on server side and store it in database:
<?php
$source_time = '2011-07-21 17:00';
$source_offset = '-0700'; // PDT
$local_timestamp = strtotime($source_time . ' ' . $source_offset); // 2011-07-22 05:00 PKT (SERVER TIME)
list(
$temp_hh,
$temp_mm
) = explode(':', date('P')); // returns difference between SERVER TIME and GMT
$local_offset = $temp_hh * 3600 + $temp_mm * 60;
$gmt_timestamp = $local_timestamp + $local_offset;
echo date("Y-m-d H:i:s", $gmt_timestamp); // 2011-07-21 10:00:00
// THIS is what you store in your database
// Same as 2011-07-21 17:00:00 minus 7 hours
Without the timezone information your calculations will be unreliable.
Edit #2
Actually... it is much simpler:
<?php
$source_time = '2011-07-21 17:00';
$source_offset = -7.0; // -0700
echo date("Y-m-d H:i:s", strtotime($source_time) + $source_offset * 3600);
// 2011-07-21 10:00:00
// THIS is what you store in your database
Edit #3
<input type="text" name="time" id="time" value="07/21/2011 17:00">
<input type="text" name="offset" id="offset">
<script type="text/javascript">
document.getElementById("time").onchange = function(){
var d = new Date(this.value);
alert('Date entered: ' + d + '\nDate to GMT: ' + d.toUTCString());
}
document.getElementById("offset").value = (new Date()).getTimezoneOffset() / 60;
</script>
Demo here
A good idea is to explicitly set the timezone for your scripts. For example:
date_default_timezone_set('Europe/London');
This will make all date functions returns dates in GMT, and I believe accounting for BST too.
Hello I am living in Poland and we have a CET time.
To convert CET to GMT I am using function:
function convertCETtoGMT($timeCET)
{
date_default_timezone_set('EUROPE/London');
$time = $timeCET." CET";
$timeGMT = date('Y-m-d H:i:s', strtotime($time));
date_default_timezone_set('EUROPE/Warsaw'); //set back to CET
return $timeGMT;
}

check time for time difference in 24hr

In php i get the variable $date_time in this format -- 11-01-2010 20:48:25 . This time is GMT time. I have a 2 hour flexibility and if it exceeds 2 hours then i have to reject it. I am set in EST, but i want to do the check based on GMT only so that there is no errors in the time difference. How can i set to GMT in my php code and how do i check for the 2 hours flexible time difference? like for this example it is acceptable for any time between 11-01-2010 18:48:25 and 11-01-2010 22:48:25. Also will it be an issue if $date_time is 11-01-2010 23:48:23?
Clarification
I am doing a $date_time=$_GET['date_time'];. Then i need to check if this new $date_time if within 2 hours range of the current GMT time. if it is in the range, then i will proceed to execute that code, else i will show an error or do something else. I wanted to know how i am going to check this 2 hours range for this $date_time variable.
Here is a way how to convert your time format into a UNIX timestamp:
$date = strptime($date_time, "%m-%d-%Y %T");
$ut = mktime($date['tm_hour'], $date['tm_min'], $date['tm_sec'], 1 + $date['tm_mon'], $date['tm_mday'], 1900 + $date['tm_year']);
$now = time();
if($ut >= $now && $ut <= ($now + 7200)) { // 7200 = 2 * 60 * 60 seconds
// allowed
}
Reference: strptime, mktime, time.
Note: time() always returns the UNIX timestamp in UTC (regardless of time settings). So this assumes that the $date_time timestamp is a GMT time.
Working example (of course you have to provide a valid GMT time for $date_time).
Note 2: If the input time is not in GMT, you can set the timezone with date_default_timezone_set (affects mktime but not time).
Working example (change time and timezone accordingly)
If PHP >= 5.3 (you've got a seriously weird format BTW):
date_default_timezone_set('EST');
$inputtime = DateTime::createFromFormat('m-d-Y H:i:s','11-01-2010 20:48:25',new DateTimeZone("GMT"));
$diff = $inputtime->getTimestamp() - time();
if(abs($diff) > 7200){
//more then 2 hours difference.
}
If you run on PHP > 5.3, you can use DateTime for this :
$my_date = "11-01-2010 20:48:25";
$date = DateTime::createFromFormat('m-d-Y H:i:s', $my_date);
$date_lower = DateTime::createFromFormat('m-d-Y H:i:s', $my_date);
$date_upper = DateTime::createFromFormat('m-d-Y H:i:s', $my_date);
$date_lower->sub(new DateInterval('PT2H'));
$date_upper->add(new DateInterval('PT2H'));
var_dump($date >= $date_lower && $date <= $date_upper); // bool(true)
I find it more readable.
You can also use another timezone if necessary, check the third argument of createFromFormat.
I suggest you to never pass times and dates with format string. Just convert it later. You just pass the timestamp as a get variable and then you format it in the script.
It's the best solution and also the cleanest.
Then use the following code:
$flexibility = X seconds;
if ($date_time < time() - $flexibility or $date_time > time() + $flexibility)
{ /*Error*/ }

Categories