PHP Timestamp into DateTime - php

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

Related

DateTimeZone only handles offsets in one direction

I am attempting to retrieve a date that is not in GMT and convert it to GMT. To do this, I am creating two time zones (one GMT and one non-GMT) and attempting to get the offset between them. However, the offset is only correct in one direction. For this specific example, I am trying to compare GMT +4 to GMT. I expect to get 4hrs (14400 seconds) when I compare the the GMT timezone to the GMT+4 timezone, and -4hrs (-14400 seconds) when I compare the GMT+4 timezone to GMT. However, when comparing the later I'm getting 0... Here is what I have
$default_timezone = new DateTimeZone(drupal_get_user_timezone());
$default_reg_date = new DateTime($reg_date_string, $default_timezone);
$gmt_timezone = new DateTimeZone('UTC');
$gmt_reg_date = new DateTime($reg_date_string, $gmt_timezone);
// Returns as 14400
$default_gmt_offset = $default_timezone->getOffset($gmt_reg_date);
// Returns as 0
$gmt_default_offset = $gmt_timezone->getOffset($default_reg_date);
Why can't I get the right number, what am I doing wrong? Does retrieving the offset only work one way?
Note: in this specific example, drupal_get_user_timezone() is returning GMT+4
From the PHP documentation :
This function returns the offset to GMT for the date/time specified in the datetime parameter. The GMT offset is calculated with the timezone information contained in the DateTimeZone object being used.
The function works with 2 logics steps :
Convert the date into the timezone on which the function is applied
Get the offset from GMT
So calling this function on new DateTimeZone('UTC') will always returns 0
If you want to convert a date into UTC, you can use the setTimeZone function :
$date_string = '2020-05-01 09:11:00' ;
$date = new DateTime($date_string, new DateTimeZone('Europe/Brussels'));
echo $date->format('c') ; // 2020-05-01T09:11:00+02:00
$date->setTimeZone(new DateTimeZone('UTC'));
echo $date->format('c') ; // 2020-05-01T07:11:00+00:00

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();

strtotime doesn't return false with a valid timestamp

Any idea why this
strtotime('1356532858') //Wed, 26 Dec 2012 14:40:58 GMT
returns 28043243813 while
strtotime('1356055871') //Fri, 21 Dec 2012 02:11:11 GMT
returns false?
I'm searching for a solution where I can translate any common date string into a valid timestamp. Unfortunately there are some (valid) timestamps included as well
maybe you could try to use strtotime only if string is not 10-digit?
$str = '1356055871';
$timestamp = (preg_match('/\d{10}/',$str,$match))?(int)$str:strtotime($str);
echo $timestamp;
Regarding the question why you receive a value on first execution, and false in second one, this is because 1356532858 is interpreted as some valid date, although is not what you're expecting:
echo date("Y-m-d H:i:s",strtotime('1356532858'));
// outputs: 2858-08-27 13:56:53
strtotime can accept your timestamp, but should have a leading #:
echo date("Y-m-d H:i:s",strtotime('#1356532858'));
// outputs: 2012-12-26 15:40:58
Try putting a '#' in front of your timestamp. This will instruct strtotime that this is a timestamp in Unix format:
var_dump(strtotime('#1356055871'));
Source

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 display a date as iso 8601 format with PHP

I'm trying to display a datetime from my MySQL database as an iso 8601 formated string with PHP but it's coming out wrong.
17 Oct 2008 is coming out as: 1969-12-31T18:33:28-06:00 which is clearly not correct (the year should be 2008 not 1969)
This is the code I'm using:
<?= date("c", $post[3]) ?>
$post[3] is the datetime (CURRENT_TIMESTAMP) from my MySQL database.
Any ideas what's going wrong?
The second argument of date is a UNIX timestamp, not a database timestamp string.
You need to convert your database timestamp with strtotime.
<?= date("c", strtotime($post[3])) ?>
Using the DateTime class available in PHP version 5.2 it would be done like this:
$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');
As of PHP 5.4 you can do this as a one-liner:
echo (new DateTime('17 Oct 2008'))->format('c');
Procedural style :
echo date_format(date_create('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
Object oriented style :
$formatteddate = new DateTime('17 Oct 2008');
echo $datetime->format('c');
// Output : 2008-10-17T00:00:00+02:00
Hybrid 1 :
echo date_format(new DateTime('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
Hybrid 2 :
echo date_create('17 Oct 2008')->format('c');
// Output : 2008-10-17T00:00:00+02:00
Notes :
1) You could also use 'Y-m-d\TH:i:sP' as an alternative to 'c' for your format.
2) The default time zone of your input is the time zone of your server. If you want the input to be for a different time zone, you need to set your time zone explicitly. This will also impact your output, however :
echo date_format(date_create('17 Oct 2008 +0800'), 'c');
// Output : 2008-10-17T00:00:00+08:00
3) If you want the output to be for a time zone different from that of your input, you can set your time zone explicitly :
echo date_format(date_create('17 Oct 2008')->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2008-10-16T18:00:00-04:00
For pre PHP 5:
function iso8601($time=false) {
if(!$time) $time=time();
return date("Y-m-d", $time) . 'T' . date("H:i:s", $time) .'+00:00';
}
Here is the good function for pre PHP 5:
I added GMT difference at the end, it's not hardcoded.
function iso8601($time=false) {
if ($time === false) $time = time();
$date = date('Y-m-d\TH:i:sO', $time);
return (substr($date, 0, strlen($date)-2).':'.substr($date, -2));
}
The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:
// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z
// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z
// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z
//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z

Categories