Get the correct hour for a UNIX timestamp - php

I think this is a stupid question, but seems that I cannot find the answer.
I have this timestamp: 1295598602.
In my php script I have:
$date = date('Y-m-d', 1295598602);
$hour = date('H', 1295598602) . ':00';
This returns:
Date: 2011-01-21
Hour: 03:00
Now I went to an online conversion site to test this. I used this one.
But it seems that for this timestamp value it is
Fri, 21 Jan 2011 08:30:02 GMT
Now, which one is correct?

Use correct timezone:
>> date_default_timezone_get();
'UTC'
>> date('Y-m-d h:i:s',1295598602);
'2011-01-21 08:30:02'
>> date_default_timezone_set('CET');
true
>> date('Y-m-d h:i:s',1295598602);
'2011-01-21 09:30:02'
>> date_default_timezone_set('UTC');
true
>> date('Y-m-d h:i:s',1295598602);
'2011-01-21 08:30:02'

In GMT / UTC (they're almost but not quite exactly the same) that timestamp is indeed Fri, 21 Jan 2011 08:30:02 GMT.
If you're in a different timezone but always want GMT you'll need to use the gmdate() function instead of date().

Both are correct. In the code snippet PHP adjusts for timezone. Try date_default_timezone_set('UTC'); to get proper unadjusted values.

Another option is to set the default timezone for your script.
For example,
date_default_timezone_set('Europe/London');
$timestamp = '1295598602';
echo date('Y-m-d H:i:s', $timestamp);
would get you the same result as the online conversion tool is showing.
There are a number of timezone-related function in PHP that will allow you to modify which time zone is being shown.
You can check the PHP docs for a list of your options: http://www.php.net/manual/en/ref.datetime.php

According to date() function description,
timestamp is optional and defaults to
the value of time().
And according to time() function description, it returns GMT timestamp.
So, PHP does conversion to your time zone, while onlineconversion.com does not.

Related

Arithmatic signs are not working properly in strtotime

I want to fetch the correct date as per the timezones.
ex. I have a time zone +5:30 from GMT. if GMT is 30 aug 2016 1:00 pm then for gmt+5:30 should give me 30 Aug 2016 6:30 pm however, adding timezones like that actually subtracts it rather adding.
I have this code:
$a=date('Y-m-d H:i:s');
which gives me 2016-08-30 07:36:01 as per GMT which is correct.
$b="+5:30";
$c=(strtotime($a.$b));
echo($c);
it gives me 30 Aug 2016 02:08:25 which is wrong I should get 30 Aug 2016 13:10:32.
What I mean is, if I am adding the timezone value it is getting subtracted and if I do same with -5:30 as timezone I get the correct result. Can somebody please suggest what am I doing wrong or how this should work actually.
Use DateTimeZone and DateTime objects to make it more obvious while working with timezone offsets:
$a = "2016-08-30 07:36:01";
$b = "+5:30";
$gmtTz = new \DateTimeZone("GMT");
$offset = new \DateTimeZone($b);
$dt = new \DateTime($a, $gmtTz);
$dt->setTimezone($offset);
echo $dt->format("Y-m-d H:i:s"); // "016-08-30 13:06:01"
Try this:
Solution 1 :
$minutesToBeAdded = 330;
$currentDate = date('Y-m-d H:i:s');
$currentTime = new DateTime($currentDate);
$currentTime->add(new DateInterval('PT' . $minutesToBeAdded . 'M'));
$newTime = $currentTime->format('Y-m-d H:i');
Solution 2 :
$currentDate = date('Y-m-d H:i:s');
$dateTime = new DateTime($currentDate);
$dateTime->modify('+330 minutes');
Solution 3 :
$currentDate = date('Y-m-d H:i:s');
$newTime = strtotime($currentDate . ' + 330 minute');
echo date('Y-m-d H:i:s', $newTime);
I think the above solution will be helpful for you though I haven't tested it.
When you use functions like date and strtotime, PHP converts the inputs you supply according to your date.timezone configuration in PHP, which may not be UTC. So it's important to check, or explicitly set, the timezone before you do the conversion.
$date = "30 Aug 2016 1:00 pm";
date_default_timezone_set("UTC");
var_dump(date_default_timezone_get()); // gives us "UTC"
var_dump(date("Y-m-d H:i:s", strtotime($date))); // 2016-08-30 13:00:00
var_dump(date("Y-m-d H:i:s", strtotime($date . "+5:30"))); // 2016-08-30 07:30:00
So now you're wondering why you just went back in time 5 hours and 30 minutes. Well, if you look at the actual Unix timestamp from strtotime the truth is revealed about what date and strtotime are doing.
var_dump(strtotime("30 Aug 2016 1:00 pm"), strtotime("30 Aug 2016 1:00 pm +5:30"));
This gives you...
int(1472562000)
int(1472542200)
In the first case, strtotime takes the input string "30 Aug 2016 1:00 pm" and converts it to a Unix timestamp under the assumption that we're currently in UTC. In the second case, it takes the input string "30 Aug 2016 1:00 pm +5:30", which already has a GMT offset of +5:30. So it assumes that we're 1:00 PM in GMT+0530, and it tries to convert that back to UTC (i.e +0000), meaning it now needs to subtract 5 hours and 30 minutes to get to UTC, which gives you "30 Aug 2016 7:30 am"
It's easier to avoid all this confusion when you use DateTime, because you can explicitly specify the timezone or the GMT offset and not be subject to implicit timezone conversion. Also, it's important to note that in PHP a timezone is more than just a GMT offset. PHP uses the Olson Timezone Database to reliably and accurately convert date/time information across different timezones, since GMT offsets can actually vary throughout the year in different timezones.
// DateTime doesn't try to convert this because you told it what the timezone is
$dt = new DateTime("30 Aug 2016 1:00 pm", new DateTimezone("UTC"));
// now lets try with the offset
$dt->setTimezone(new DateTimezone("Asia/Kolkata"));
var_dump($dt->format("j M Y g:i a")); // "30 Aug 2016 6:30 pm"
Notice, there's no need for you to actually mess around with how many hours/minutes to add/subtract. PHP figures it all out by looking up the needed timezone information in the database. Because we correctly specified the timezone supplied and the timezone converted we can rest assured we always have the accurate time regardless of how many times we subsequently convert between timezones. It's a far more reliable abstraction than what you're trying to do.

Using strtotime() PHP and revert back trough gmdate() is not returning same date

I have a string $StartDate = "2015-09-23" (should be like yyyy-mm-dd).
Than I make $UdtStart= strtotime($StartDate) that returns 1442980800;
Well if I go to this link it return back "Wed, 23 Sep 2015 04:00:00 +0000".
First, why do we have 04:00:00 added?
Than, if I do this $back=gmdate("Y-m-d H:i:s", ($UdtStart)); I will have "2015-09-26 04:00:00".
What am I missing?
$UdtStart= strtotime($StartDate);
$back=gmdate("Y-m-d H:i:s", ($UdtStart));
Wed, 23 Sep 2015 04:00:00 +0000
Note that +0000 on the end, that means the time is UTC. As per the PHP strtotime() doco:
Each parameter of this function uses the default time zone unless a time zone is specified in that parameter.
The gmdate is for Greenwich Mean Time (and really should be called something like utcdate nowadays), so you're asking for the data in a different foramt from what you gave it.
I'd be willing to bet money that you're in a timezone four hours removed from UTC, which is why you're seeing that.
If you want local time, use date() rather than gmdate(). The gmdate doco states:
Identical to the date() function except that the time returned is Greenwich Mean Time (GMT).

How to convert UTC datetime to another timezone?

How can i convert a date like this: 2012-07-16 01:00:00 +00 (it's in the UTC +00:00 timezone) to UTC +04:00 timezone? Ensuring that daylight saving will be handelled correctly?
Use DateTime and DateTimeZone.
$date = new DateTime('2012-07-16 01:00:00 +00');
$date->setTimezone(new DateTimeZone('Europe/Moscow')); // +04
echo $date->format('Y-m-d H:i:s'); // 2012-07-15 05:00:00
To help with the solution, you need to get the last part of the string (the offset part) and look it up against a simple lookup. you can use a regex or substr() (maybe) to get the offest part. Then, when you have a + or - value, use a maximum of 24 lookups against possible timezones which you can use with PHP's possible timezones - if the offset is the same, who cares what the actual country/location is?
The use date_default_timezone_set to apply the right one.
The DateTimeZone constructor can explicitly accept a UTC offset, which I understand you have.
//So For 'Asia/Kolkata' you need to use
$timeZone = new DateTimeZone('+0530');
// Example
$utc = new DateTime("1960-08-08T20:40:00Z");
echo $utc->format('Y-m-d H:i:s T')."<br>";
$tz =new DateTimeZone('+0530');
$utc->setTimezone($tz);
echo $utc->format('Y-m-d H:i:s T');
Output:
1960-08-08 20:40:00 Z
1960-08-09 02:10:00 GMT+0530
I guess this is easiest and simplest way to convert time to any given Offset
Documentation:
http://php.net/manual/en/datetimezone.construct.php
Note: per that documentation link, this new constructor usage has been available since PHP version 5.5.10.
You can also use GMT time also and convert it to your requirement afterwards
<?php
echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
?>
GMT refers Greenwich Mean Time which is common all over the world.

strtotime('today') returning incorrect time?

I am trying to create a select list starting from the current date of the user. I want it so that it is set to midnight in unix timestamp format.
This is all I'm doing:
$today = strtotime('today');
echo $today;
This is my result:
1333144800
which is: Fri, 30 Mar 2012 22:00:00 GMT according to Epoch Converter (incorrect by a couple hours.)
If you want strtotime() to return a timestamp relative to UTC (00:00:00 UTC instead of e.g. 00:00:00 UTC+2, if your system is set to a timezone with an offset of 2 hours against UTC/GMT), you need to specify that:
$today = strtotime('today UTC');
GMT (+0) time
echo $today = strtotime('today GMT');
echo "<br>" . $today = date("d-m-Y H:i:s", $today);
We expect that your server runs at GMT - that is the best (for maneuvering with time displays later). If not, you MUST adjust php.ini set this "date.timezone = GMT".
When you get that done, you will see 00:00 with my codes.
Then, you must develop function (ie DisplayDate()) in your script to display dates of your website correctly if
youre not in GMT area
or/and if you want for your users to see times in their timezone with timezone selection for example.
DisplayDate() should include support for daylight changes also (0, or +1 hour / summer and winter time).
strtotime( $time )
is designed to return a unix timetamp, meaning, it will return the number of seconds since jan 1, 1970. http://www.php.net/manual/en/function.strtotime.php
To get around this, use something like:
$today = date("d/m/Y H:i:s", strtotime('today'));
echo $today;
You might have to specifically set the time as well as the day:
$today_midnight = strtotime('today UTC 00:00');
You should check the timezone configuration in your php.ini file. In my case (I live in El Salvador) I had to change it like this:
date.timezone = America/El_Salvador

PHP: Get Time for Current Region

I have a timezone of the user(he chooses it from a list)
I have a time in UTC(not current time)
So I need something like GetTimeForRegion(time, timezone) for PHP. Is there such functions or libraries or services?
you can use DateTime::setTimezone(). If your UTC date is an UNIX timestamp, you can use some code like this :
$date = new DateTime();
$date->setTimezone(new DateTimeZone('UTC'));
$date->setTimestamp(1297869844);
$date->setTimezone(new DateTimeZone('Europe/Paris'));
echo $date->format('Y-m-d H:i:s');
// Will print 2011-02-16 16:24:04
date('r') or date('c') may help you.
echo date('r') prints Thu, 16 Feb 2011 16:01:07 +0200
echo date('c') prints 2011-02-16T16:01:07+02:00
You need to look at the Date/Time API in PHP. I strongly advise you to stay away of gmdate and older date functions in php.
In your case, you should ask the user for its Olson based time zone.
The code of Artefact2 will do the trick.
please write this instead :
$date = date("Y-m-d H:i:s" , time());
so Y it means year m means month d means day
H get hours from 0 - 24
h get hours from 0 to 12
i get minutes
s get seconds

Categories