i am working on a Cakephp 2.x .. well the problem which i have has nothing to do this with cakephp .. so the scenario is i have a page called settings in which user sets his timezone according to his country and in database i am storing the time in gmt format in Userinfo table
so in userinfo table the gmt time is
5.00
now in my other tables i have a field called datetime in which i am storing the datetime in this format
2013-06-14 10:28:00
now on my view pages i want to display the data with dateTime of particular user ...
what i want is i want to add the gmt to this datetime so i can get the final datetime according to the user country ... hope you undertstand what i want to say...
Use Cake's build-in Timehelper. Add the Helper in your controller public $helpers = array('Time'); and then in your view:
$this->Time->format($format = NULL, $date, $default = false, $timezone = NULL)
In your case that'll be: $this->Time->format('d-m-Y H:i', $data['data']['datetime'], NULL, $data['User']['timezone']);
Good luck with that. :)
NOTE:
Since CakePHP 2.2 the order of $format and $date is changed. The way I explained is for CakePHP 2.2 or higher.
<?php
$utc = gmdate("M d Y H:i:s"); // place your gmt timestamp here
echo $utc."<br>";
$offset = date('Z'); //gets offset from gmt
echo $offset."<br>";
$localtime = strtotime($utc) + $offset; // adjusts to localtime.
echo date("M d Y H:i:s", $localtime);
?>
echo (new DateTime('2012-07-16 01:00:00 UTC'))
-> setTimezone(new DateTimeZone('GMT+8') )
->format('Y-m-d H:i:s');
will ouput
2012-07-16 09:00:00
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 want to get a real timestamp of given time in specified timezone for using in frontend.
Currently i can set a timezone, and get the time for it. But i can't get a new one timestamp.
Carbon::setToStringFormat('U'); // Set __toString format
$instance = Carbon::createFromTimestamp('1460014482', "Europe/Kiev"); // Set global server timezone (or pickup from default PHP setting)
$instance->setTimezone("Indian/Maldives"); // Set user timezone
var_dump($instance->format('d M Y H:i:s')); // Shows the correct time +2 hours from Europe/Kiev
var_dump((string)$instance); // Shows the same timestamp specified in createFromTimestamp
var_dump(date('d M Y H:i:s', (string)$instance)) // So it won't show the timezone datetime
Explain how i can get a timestamp of time for a given timezone.
Thanks!
You need to use the function createFromFormat to use setTimezone. Here is an example for your code:
$originalDate = date("Y-m-d H:i:s", '1460014482');
$instance = Carbon::createFromFormat('Y-m-d H:i:s', $originalDate, 'Europe/Kiev');
$instance->setTimezone("Indian/Maldives");
Hope it helps.
I know its not a complete solution. But it works for my requirements.
Currently need to override __toString method of Carbon class, which i use to display date timestamp.
public function __toString()
{
return static::$toStringFormat == 'U' ? (string)strtotime($this->format('Y-m-d H:i:s')) : $this->format(static::$toStringFormat);
}
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.
thanks for reading.
Just need to know how i convert datetime gotten from my sql tables in gmtime to datetime in user timezone.
the following is my code but doesn't seem to work..
//WHERE $post_arr[5] is date from sql
$user_date=convert_date_for_user($post_arr[5]);
function convert_date_for_user($date_time){
$user = JFactory::getUser();
$db = JFactory::getDBO();
$timezone=$user->getParam('timezone');
echo $tz_offset;
$user_date = JFactory::getDate($date_time,$timezone);
$user_date_str = $user_date->toUnix(true);
return $user_date_str;
}
It converts but I'm getting all the wrong time from the above code.
The simplest way to do it:
$useUserTimeZone = true;
JHtml::date($sqlGmtTimestamp , 'D F n, Y', $useUserTimeZone);
$sqlGmtTimestamp takes GMT timestamp/datetime
$useUserTimeZone is a flag to use user's timezone, otherwise server's timezone will be used.
more details here: http://docs.joomla.org/API16:JHtml/date
You don't specify your Joomla version but, did you try Joomla's JDate class directly?
// Get the User and their timezone
$user = JFactory::getUser();
$timeZone = $user->getParam('timezone', 'UTC');
// Create JDate object set to now in the users timezone.
$myDate = JDate::getInstance('now', $timeZone);
// Gets the date as UNIX time stamp.
$myDate->toUnix():
// For your example using a method
function convert_date_for_user($date_time)
{
// Get the User and their timezone
$user = JFactory::getUser();
$timeZone = $user->getParam('timezone', 'UTC');
// Create JDate object set to now in the users timezone.
$myDate = JDate::getInstance($date_time, $timeZone);
return $myDate->toUnix();
}
This is the function that works for me:-
//WHERE date_time is the format of the date taken directly from database(ie: 0000-00-00 00:00:00)
function convert_time_zone($date_time){
$user =& JFactory::getUser();
$db = JFactory::getDBO();
$timezone=$user->getParam('timezone','UTC');
$time_object = new DateTime($date_time, new DateTimeZone('UTC'));
$time_object->setTimezone(new DateTimeZone($timezone));
$user_datetime=$time_object->format('Y-m-d H:i:s');
//SELECT ONLY 1 line below
return $user_datetime; //WOULD RETURN DATETIME IN 0000-00-00 00:00:00
//OR
return $time_object->getTimestamp(); //WOULD RETURN DATETIME IN UNIX TIMESTAMP
}
Its a little out of the way as i was hoping to use functions included in the joomla API to do it. If anyone could provide a better solution please do. and i select it as the right answer.
With Joomla 2.5+ (i think), you can use the following code
echo JHtml::_('date', $input, $format, $tz, $gregorian);
$input can be one of the following values:
"now" for the current time (DEFAULT)
A date/time string in a format accepted by date()
$format can be one of the following values:
NULL to use the default locale based format (DEFAULT)
A date format specification string (see http://php.net/manual/en/function.date.php)
$tz can be one of the following values:
TRUE to use the user's time zone (DEFAULT). Note: If the user's time zone is not set then the global config time zone is used.
FALSE to use global config time zone
NULL for no conversion
A timezone string (eg: "America/Los_Angeles", see http://php.net/manual/en/timezones.php)
$gregorian can be one of the following values:
TRUE to use Gregorian calendar
FALSE to NOT use Gregorian calendar (DEFAULT)
Having tried all the given possible solutions here and not getting the date in the user's timezone (Joomla! v.3.9.14), here's my (proven) solution:
$oUser_TZ = JFactory::getUser()->getTimezone();
$aUser_tz = (array)$oUser_TZ; // almost sure this step is not that necessary
$full_date = JFactory::getDate('now', $aUser_tz['timezone']); // pretty sure $oUser_tz->timezone will work
// I had try to use $full_date->Format('Y-m-d H:i:s') but it was giving me the non-converted-to-wanted-timezone date, so
$date_converted = substr($full_date, 0, 19);
date_converted gives me the date in format Y-m-d H:i:s and in the wanted timezone.
Try This:
$date = JFactory::getDate(); // now - 2014-03-11 08:45:22
$date->setOffset(8); // UTC+8
echo $date->toMySQL(); // wrong - 2014-03-11 08:45:22
echo '<br />';
echo $date->toFormat(); // right - 2014-03-11 16:45:22
JHtml::date($post_arr[5]);
If you want a different format, use the second parameter:
JHtml::date($post_arr[5], DateTime::RFC2822);
Which is equivalent to:
1. Create a JDate object with an UTC date read from the database
2. Get the correct Time Zone in Jomla Global Configuration and User Configuration
3. Call setTimeZone() to convert your JDate object to user local time
4. Call format() to format the JDate object as a well formatted string
Progress :
1. I retireved date from a collection.
Example format : Fri Oct 05 14:59:31 +0000 2012
2. I was able to change its format.
CODE USED :
$cur=$col->find(array(),array("created_at"=>1,"_id"=>0));
// created_at = contains Date value
$cur_all=$col->find();
while($doc=$cur_all->getNext())
{
$doc2=$cur->getNext();
$pieces = implode(" ", $doc2);
//converted the array to string with space delimiting
if($pieces!=NULL)
{
$date1 = date_create_from_format("D M d G:i:s +O Y", $pieces);
echo date_format ( $date1 , 'Y-m-d G:i:s' );
//This is the format i would like to update in mongodb..
$filter = array('_id'=>new MongoId($doc['_id']));
$update = array('$set'=>array('created_at'=> newMongoDate($date2)));
$col->update($filter,$update);
}
}
QUESTION :
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
P.S : I did a lot of research on Stackoverflow (And other places, as well.) but I could not come to any conclusions. That is why this question. Let me know if there are any clarifications
Hmm even though you have explained your background well your actual question:
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
Is a bit confusing.
MongoDB will always save the date in one format and one format only when using ISODate: http://en.wikipedia.org/wiki/ISO_8601 (otherwise known as MongoDate in PHP) and it is probably best to not mess with this status quo.
So I would recommend you use the format Y-m-d G:i:s only as display, i.e.:
$date1 = new MongoDate();
var_dump(date('Y-m-d G:i:s', $date1->sec));
And you use the original $date1 object to actually save to the database.
Of course this would change if you were to create a date in your specified format however here is a piece of code for an example:
$date1 = new MongoDate();
$date2 = new MongoDate(strtotime(date ( 'Y-m-d G:i:s', $date1->sec )));
var_dump(date('Y-m-d G:i:s', $date2->sec));
You can use the $date2 as the date to save into MongoDB formed from the specific format you want.
look at http://php.net/manual/en/class.mongodate.php
your code should create a date using a unix timestamp
$date2 = ('23rd April 2013');
$update = array('$set'=>array(
'created_at'=> new MongoDate(strtotime($date2))
));
http://www.php.net/manual/en/function.strtotime.php