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.
Related
So I've checked the list of supported time zones in PHP and I was wondering how could I include them in the date() function?
Thanks!
I don't want a default timezone, each user has their timezone stored in the database, I take that timezone of the user and use it. How? I know how to take it from the database, not how to use it, though.
For such task, you should really be using PHP's DateTime class. Please ignore all of the answers advising you to use date() or date_set_time_zone, it's simply bad and outdated.
I'll use pseudocode to demonstrate, so try to adjust the code to suit your needs.
Assuming that variable $tz contains string name of a valid time zone and variable $timestamp contains the timestamp you wish to format according to time zone, the code would look like this:
$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');
DateTime class is powerful, and to grasp all of its capabilities - you should devote some of your time reading about it at php.net. To answer your question fully - yes, you can adjust the time zone parameter dynamically (on each iteration while reading from db, you can create a new DateTimeZone() object).
If I understood correct,You need to set time zone first like:
date_default_timezone_set('UTC');
And than you can use date function:
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:
$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp(123456789);
echo $dt->format('F j, Y # G:i');
Use the DateTime class instead, as it supports timezones. The DateTime equivalent of date() is DateTime::format.
An extremely helpful wrapper for DateTime is Carbon - definitely give it a look.
You'll want to store in the database as UTC and convert on the application level.
It should like this:
date_default_timezone_set('America/New_York');
U can just add, timezone difference to unix timestamp.
Example for Moscow (UTC+3)
echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);
Try this. You can pass either unix timestamp, or datetime string
public static function convertToTimezone($timestamp, $fromTimezone, $toTimezone, $format='Y-m-d H:i:s')
{
$datetime = is_numeric($timestamp) ?
DateTime::createFromFormat ('U' , $timestamp, new DateTimeZone($fromTimezone)) :
new DateTime($timestamp, new DateTimeZone($fromTimezone));
$datetime->setTimezone(new DateTimeZone($toTimezone));
return $datetime->format($format);
}
this works perfectly in 2019:
date('Y-m-d H:i:s',strtotime($date. ' '.$timezone));
I have created this very straightforward function, and it works like a charm:
function ts2time($timestamp,$timezone){ /* input: 1518404518,America/Los_Angeles */
$date = new DateTime(date("d F Y H:i:s",$timestamp));
$date->setTimezone(new DateTimeZone($timezone));
$rt=$date->format('M d, Y h:i:s a'); /* output: Feb 11, 2018 7:01:58 pm */
return $rt;
}
I have tried the answers based on the DateTime class. While they are working, I found a much simpler solution that makes a DateTime object timezone aware at the time of creation.
$dt = new DateTime("now", new DateTimeZone('Asia/Jakarta'));
echo $dt->format("Y-m-d H:i:s");
This returns the current local time in Jakarta, Indonesia.
Not mentioned above. You could also crate a DateTime object by providing a timestamp as string in the constructor with a leading # sign.
$dt = new DateTime('#123456789');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('F j, Y - G:i');
See the documentation about compound formats:
https://www.php.net/manual/en/datetime.formats.compound.php
Based on other answers I built a one-liner, where I suppose you need current date time. It's easy to adjust if you need a different timestamp.
$dt = (new DateTime("now", new DateTimeZone('Europe/Rome')))->format('d-m-Y_His');
If you use Team EJ's answer, using T in the format string for DateTime will display a three-letter abbreviation, but you can get the long name of the timezone like this:
$date = new DateTime('2/3/2022 02:11:17');
$date->setTimezone(new DateTimeZone('America/Chicago'));
echo "\n" . $date->format('Y-m-d h:i:s T');
/* Displays 2022-02-03 02:11:17 CST "; */
$t = $date->getTimezone();
echo "\nTimezone: " . $t->getName();
/* Displays Timezone: America/Chicago */
$now = new DateTime();
$now->format('d-m-Y H:i:s T')
Will output:
29-12-2021 12:38:15 UTC
I had a weird problem on a hosting. The timezone was set correctly, when I checked it with the following code.
echo ini_get('date.timezone');
However, the time it returned was UTC.
The solution was using the following code since the timezone was set correctly in the PHP configuration.
date_default_timezone_set(ini_get('date.timezone'));
You can replace database value in date_default_timezone_set function,
date_default_timezone_set(SOME_PHP_VARIABLE);
but just needs to take care of exact values relevant to the timezones.
I have a bit of PHP code:
$exd = date_create('01 Dec, 2015');
$exd = date_format($exd, 'Y-m-d');
echo $exd;
Which is used for formatting the date. The expected output would be 2015-12-01 but it returns 2016-12-01. What am i missing?
Use createFromFormat method first, provide the input format:
$exd = DateTime::createFromFormat('d M, Y', '01 Dec, 2015');
// arguments (<format of the input>, <the input itself>)
$exd = date_format($exd, 'Y-m-d'); // then choose whatever format you like
echo $exd;
The date_create() function accepts only the parameter link, This function is also and alias function of DateTime::__construct()
check the function date_create_from_format() its also a alias function of DateTime::createFromFormat(). Refer link
$exd = date_create_from_format('j M, Y', '01 Dec, 2015');
//$exd = date_create('01 Dec, 2015');
$exd = date_format($exd, 'Y-m-d');
echo $exd;
It can be a date function call simply. Use stringtotime for exact/precise date/time value
date("Y-m-d",strtotime("01 Dec 2015"))
When you run this code the out put will show
2015-12-01
this is because of the comma in the string which terminates the date string in the compiler. If you specify exactly the timezone (like
$timezone = 'America/New_York) . parameter you can show precise time as well.
i got the solution of your bug
that is date_format(datae_variable,date_format);
<?php
$exd = date_create('01 Dec, 2015');
$exd1 = date_format($exd,"Y-m-d");//here you make mistake
echo $exd1;
?>
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);
}
So I have the date like this in wordpress, I get it from a custom metabox where is stored like this, 23/02/2012, now how can I set wp_locale in WP or something like that, and I need to convert the date to: Monday 23 February 2012, but I need also to set the language, thats why I need that wp_locale because that output will be in Dutch.Thank you
The date format can be converted with the code below as a guide.
date('l j F Y', strtotime(str_replace('/', '-', '23/02/2012')))
The str_replace is necessary because with / PHP assumes m/d/y American date format, not the European d/m/y.
As for doing this in Wordpress with i18n support, you might consider http://codex.wordpress.org/Function_Reference/date_i18n
date_i18n('l j F Y', strtotime(str_replace('/', '-', '23/02/2012')))
I guess there are other ways to do this, but I'd do it as follows:
Upon 'save_post':
$date = explode ('/',$_POST["date_field"]);
$date = $date[1].'/'.$date[0].'/'.$date[2]; // dd/mm/yyyy to mm/dd/yyyy
$s = strtotime($date); /* UNIX TIMESTAMP */
and then store the Unix timestamp in the database.
Upon 'amdin_init' you'll need to do the exact opposite to load the date in the right format in the metabox:
global $post;
$custom = get_post_custom($post->ID);
if ($custom["date_field"][0]) {
$d = date("d/m/Y",$custom["date_field"][0]); // convert unix timestamp
} else {
$d = "";
}
And in your template file, use php functions setlocale and strftime to display the date:
$custom = get_post_custom($post->ID);
$d = $custom["date_field"][0];
setlocale(LC_TIME, 'nl_NL');
$s = strftime('%#d %B %Y',$s);
This should output something like 13 January 2012.
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