Using strtotime with TimeZone - php

I have a problem. I want to convert this DateTime: 2018-10-28 02:00:00 to a TimeStamp. Now the TimeStamp I am looking for is: 1540684800, but with my code I get this TimeStamp: 1540688400. I know it has something to do with my TimeZone, but I don't know how I can fix this.
I live in the Netherlands in Amsterdam.
Here is my code:
$LoopDateTime = "2018-10-28 02:00:00";
$search_key = (strtotime($LoopDateTime)*1000);
Can someone help me?

The time zone identifier for Amsterdam is Europe/Amsterdam and 1540688400 is the correct timestamp. There's surely an online tool to check but you can also verify it from PHP itself:
$date = new DateTime("#1540688400");
$date->setDateTimeZone(new DateTimeZone('Europe/Amsterdam'));
echo $date->format('r'); // Sun, 28 Oct 2018 02:00:00 +0100
However your code is not robust because depends on the configured timezone. You can just set it explicitly in a number of ways, e.g.:
$LoopDateTime = "2018-10-28 02:00:00";
$search_key = strtotime($LoopDateTime . ' Europe/Amsterdam') * 1000;
var_dump($search_key); // int(1540688400000)
Or:
date_default_timezone_set('Europe/Amsterdam');
$LoopDateTime = "2018-10-28 02:00:00";
$search_key = strtotime($LoopDateTime) * 1000;
var_dump($search_key); // int(1540688400000)
P.S. If I'm not wrong Sunday 28 Oct 2018 02:00:00 +0100 is the exact moment when most Europe has just switched from CEST (+0200) to CET (+0100).

Related

PHP create from format not formatting time correctly

I have this time string from sql 00:05:00 and I need a timestamp from it but can't seem to get it. I have also tried strtotime.
What am I doing wrong?
$NonBillable = '00:05:00';
$NonBillable = DateTime::createFromFormat('H:i:s', $NonBillable)->getTimestamp();
echo $NonBillable;
$NonBillable = DateTime::createFromFormat('H:i:s', '00:05:00');
echo $NonBillable->getTimestamp();
It results for me 1464480300 -> Sun, 29 May 2016 00:05:00 GMT because no date has been given, it uses today.
So a simple solution to this would be:
echo $NonBillable->getTimestamp() - time();

Detect BST in php

I am building a booking system in php that offers session times for people to book outdoor activities.
In the summer months, there is an extra session available at the end of the day, because of Daylight Savings, there is an extra hour in the evenings.
Year Clocks go forward Clocks go back
2014 30 March 26 October
2015 29 March 25 October
2016 27 March 30 October
2017 27 March 30 October
2018 25 March 28 October
I am using this...
$todaysDate = strtotime(date("Y-m-d"));
$bstBegin = strtotime("2015-03-29");
$bstEnd = strtotime("2015-10-25");
if($todaysDate > $bstBegin && $todaysDate > $bstEnd)
{
echo "<option value="evening">Evening Session</option>";
}
I only need to show this extra option in the select list between these dates. Is this something I will need to set manually from year to year, or is there a PHP date variable that knows the days the clocks change?
$today = strtotime(date("Y-m-d"));
if (date('I', $today)) {
echo "We're in BST!";
} else {
echo "We're not in BST!";
}
or use the DateTime object equivalent, which maintains details of all the transition dates globally
I work normally with the DateTime functions and like it very much. You have a lot of possibilities to modify a date.
But in your case you can concat the actual year to your string.
$todaysDate = strtotime(date("Y-m-d"));
$bstBegin = strtotime(date('Y')."-03-29");
$bstEnd = strtotime(date('Y')."-10-25");
I hope i have understood your problem correctly.
I have found this online very good ref : https://gist.github.com/aromig/56376f76d4fb653ba83e
public function is_BST() {
$theTime = time();
$tz = new DateTimeZone('Europe/London');
$transition = $tz->getTransitions($theTime, $theTime);
$abbr = $transition[0]['abbr'];
return $abbr == 'BST' ? true : false; }

Convert int-date to RSS PubDate RFC 822 PHP

I have a question that is making me crazy,
My Task is to parse a date from an API and transform it to RFC 822 format, because the feed that is coming out gets an validation error
the date from the API looks like this :
<review created="2012-10-23 14:51:12.0">
I have one Date in the description made via substr
$xtime = substr($review["created"], 0, 16);
$jahr = substr($xtime,0,4);
$mon = substr($xtime,5,2);
$tag = substr($xtime,8,2);
$datneu = $tag.'.'.$mon.'.'.$jahr;
this date will be rendered like :
23.10.2012
For the pubdate I made
$xtime = substr($review["created"], 0, 16);
$xxl = $pubtime . " GMT";
rendered like :
2012-10-23 14:51:12 GMT
And W3C feed validator says it´s not validate because pubDate is not in RFC 822 form
Sorry
This feed does not validate.
line 10, column 38: pubDate must be an RFC-822 date-time: 2012-10-29 11:51:23 GMT (5 occurrences) [help]
<pubDate>2012-10-29 11:51:23 GMT</pubDate>
and it needs to look like :
<pubDate>Wed, 02 Oct 2002 13:00:00 GMT</pubDate>
i can imagine a hacky solution for expressing sth like "if (month = 01){ actualmonth = Jan}" but i really don´t know how to do same with the days,
Also i´m not too comfortable with PHP but I need to solve this asap.
Hope you can help me, there must be a solution i didnt found at similiar questions
regards John
Have a look at DateTime::createFromFormat() or date_create_from_format.
http://fr2.php.net/manual/en/datetime.createfromformat.php
<?php
$date = date_create_from_format('Y-m-d H:i:s', '2012-10-23 14:51:12.0');
echo date_format($date, 'D, d M Y H:i:s');
?>
Have a look at the possible date formats
http://fr2.php.net/manual/en/function.date.php
EDIT: fixed
Hi in PHP you should look at this: function date
yeaaaaah that worked for me, amazing!
for others the exact solution for my Case was
$before = "2012-10-23 14:51:12.0";
$timetwo = substr($before, 0, 16);
$timethree = date_create_from_format('Y-m-d H:i:s', $timetwo);
$timefinal = date_format(timethree, 'D, d M Y H:i:s');
$after = $timefinal . ' GMT' ;
$after = "Mon, 23 Oct 2012 14:51:12 GMT";
thanks a lot for the quick answers you are awesome!
This worked for me....
date("r", strtotime($yourdate))
$yourdate was 2013-10-27 and I got Sun, 27 Oct 2013 00:00:00 +0000

PHP Timestamp into DateTime

Do you know how I can convert this to a strtotime, or a similar type of value to pass into the DateTime object?
The date I have:
Mon, 12 Dec 2011 21:17:52 +0000
What I've tried:
$time = substr($item->pubDate, -14);
$date = substr($item->pubDate, 0, strlen($time));
$dtm = new DateTime(strtotime($time));
$dtm->setTimezone(new DateTimeZone(ADMIN_TIMEZONE));
$date = $dtm->format('D, M dS');
$time = $dtm->format('g:i a');
The above is not correct. If I loop through a lot of different dates its all the same date.
You don't need to turn the string into a timestamp in order to create the DateTime object (in fact, its constructor doesn't even allow you to do this, as you can tell). You can simply feed your date string into the DateTime constructor as-is:
// Assuming $item->pubDate is "Mon, 12 Dec 2011 21:17:52 +0000"
$dt = new DateTime($item->pubDate);
That being said, if you do have a timestamp that you wish to use instead of a string, you can do so using DateTime::setTimestamp():
$timestamp = strtotime('Mon, 12 Dec 2011 21:17:52 +0000');
$dt = new DateTime();
$dt->setTimestamp($timestamp);
Edit (2014-05-07):
I actually wasn't aware of this at the time, but the DateTime constructor does support creating instances directly from timestamps. According to this documentation, all you need to do is prepend the timestamp with an # character:
$timestamp = strtotime('Mon, 12 Dec 2011 21:17:52 +0000');
$dt = new DateTime('#' . $timestamp);
While #drrcknlsn is correct to assert there are multiple ways to convert a time string to a datatime, it's important to realize that these different ways don't deal with timezones in the same way.
Option 1 : DateTime('#' . $timestamp)
Consider the following code :
date_format(date_create('#'. strtotime('Mon, 12 Dec 2011 21:17:52 +0800')), 'c');
The strtotime bit eliminates the time zone information, and the date_create function assumes GMT.
As such, the output will be the following, no matter which server I run it on :
2011-12-12T13:17:52+00:00
Option 2 : date_create()->setTimestamp($timestamp)
Consider the following code :
date_format(date_create()->setTimestamp(strtotime('Mon, 12 Dec 2011 21:17:52 +0800')), 'c');
You might expect this to produce the same output. However, if I execute this code from a Belgian server, I get the following output :
2011-12-12T14:17:52+01:00
Unlike the date_create function, the setTimestamp method assumes the time zone of the server (CET in my case) rather than GMT.
Explicitly setting your time zone
If you want to make sure your output matches the time zone of your input, it's best to set it explicitly.
Consider the following code :
date_format(date_create('#'. strtotime('Mon, 12 Dec 2011 21:17:52 +0800'))->setTimezone(new DateTimeZone('Asia/Hong_Kong')), 'c')
Now, also consider the following code :
date_format(date_create()->setTimestamp(strtotime('Mon, 12 Dec 2011 21:17:52 +0800'))->setTimezone(new DateTimeZone('Asia/Hong_Kong')), 'c')
Because we explicitly set the time zone of the output to match that of the input, both will create the same (correct) output :
2011-12-12T21:17:52+08:00
Probably the simplest solution is just:
DateTime::createFromFormat('U', $timeStamp);
Where 'U' means Unix epoch. See docs: http://php.net/manual/en/datetime.createfromformat.php
This is my solution:
function changeDateTimezone($date, $from='UTC', $to='Asia/Tehran', $targetFormat="Y-m-d H:i:s") {
$date = new DateTime($date, new DateTimeZone($from));
$date->setTimeZone(new DateTimeZone($to));
return $date->format($targetFormat);
}

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;
}

Categories