Change date time to UTC FORMAT - php

I need to rewrite date time format from zendframework to codeigniter
Here is Zendframe work UTC format function
function _dayToDateTime($day, $begin = true)
{
$oDate = new Date($day);
if (!$begin) {
$oDate->setHour(23);
$oDate->setMinute(59);
$oDate->setSecond(59);
}
$oDate->toUTC();
return $oDate->format('%Y-%m-%d %H:%M:%S');
}
Here is my code for codeigniter
$timeZone = new DateTimeZone('UTC');
$dt = new DateTime($from_date,$timeZone);
$dt->setTime(23, 59, 59);
echo $format=$dt->format('Y-m-d H:i:s');
But I didn't get same date result.

Try setting your default time zone as UTC
date_default_timezone_set("UTC");
echo date("Y-m-d H:i:s", time());
You can also use gmdate, see here for more reference.

Related

Format a time with timezone to local time in PHP

How can a change times that are provided with a timezone (eg. 14:00:00+02:00) to a local time (the result would be 16:00:00) when the dates are not provided.
I've tried it with the DateTime class. But since I'm only handling times, not dates, it doesn't always provide the correct results:
$time = '14:00:00+02:00';
$datetime = new DateTime($date);
$result = $datetime->format("H:i:s");
Use DateTime's setTimezone method. It will automatically change the time to match the timezone.
$date = new DateTo,e("2017-02-02 10:00:00", new DateTimeZone("+0200"));
$date->setTimezone(new DateTimeZone("-0200"));
var_dump($date->format("H:i:s"));
Will output the following:
string '06:00:00' (length=8)
$utc = new DateTimeZone("UTC");
$zone = new DateTimeZone("YOUR_TIME_ZONE");
$date = new DateTime("14:00:00+02:00", $utc);
$date->setTimezone($zone);
echo $date->format('Y-m-d H:i:s');
You can use setTimezone() function
$time = '14:00:00+02:00';
$datetime = new DateTime($time);
$result = $datetime->format("H:i:s");
echo $result;
echo '<br>';
$datetime->setTimezone(new DateTimeZone('Your_local_timezone')); // ex: UTC (+00h00) or Europe/Moscow (+4h00)
$result = $datetime->format("H:i:s");
echo $result;
You should specific your time zone, and tell DateTime to use Time zones
for example:
$time = '14:00:00+02:00';
$datetime = DateTime::createFromFormat('H:i:s+T', $time);
$datetime->setTimezone(new DateTimeZone('Europe/Warsaw'));
$result = $datetime->format("H:i:s");
echo($result);
Use +T in format pattern to say php thats date contain a Time zone, in next step u should set your timezone using setTimezone. For example i set 'Europe/Warsaw' but nothing happen coz +02:00 is CEST thats equal to 'Europe/Warsaw'
Other way is changing +02:00 to naming time zone here is a example:
$time = '14:00:00 (UTC)';
$datetime = new DateTime($time);
$datetime->setTimezone(new DateTimeZone('Europe/Warsaw'));
$result = $datetime->format("H:i:s");
echo($result);

PHP convert UTC time to local time

Am getting a UTC time from my server like the following format, my requirement is to convert the UTC time to local time. So users can see a user friendly time on their browser based on their timezone. Please help me to solve this issue. Thank you
$utc = "2014-05-29T04:54:30.934Z"
I have tried some methods but not working in my case
First
$time = strtotime($utc);
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal;
Second
$time = strtotime($utc .' UTC');
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal;
Simply use a DateTimeZone, eg
$dt = new DateTime($utc);
$tz = new DateTimeZone('Asia/Kolkata'); // or whatever zone you're after
$dt->setTimezone($tz);
echo $dt->format('Y-m-d H:i:s');
Demo ~ http://ideone.com/fkM4ct
The reason your code isn't working is most likely because your server is in UTC time. So the local time of the server is UTC.
Solution #1
One potential solution is to do the following server side and pass the epoch integer to the browser:
$utc = "2014-05-29T04:54:30.934Z";
$time = strtotime($utc); //returns an integer epoch time: 1401339270
Then use JavaScript to convert the epoch integer to the user's local time (the browser knows the user's timezone).
Solution #2
You can get the browser to send you the user's timezone. Then you can use this information to calculate the date string server side instead of browser side. See more here: https://stackoverflow.com/a/5607444/276949
This will give you the user's offset (-7 hours). You can use this information to set the timezone by looking here: Convert UTC offset to timezone or date
If this is not done via a user profile setting, it is probably easier and simpler to use a javascript time library eg. moment.js (http://momentjs.com/) to solve this problem (send all date/times in UTC and then convert them on the client end).
Javascript eg. (I am sure this can be achieved without creating two moment objects (fix that at your leisure).
function utcToLocalTime(utcTimeString){
var theTime = moment.utc(utcTimeString).toDate(); // moment date object in local time
var localTime = moment(theTime).format('YYYY-MM-DD HH:mm'); //format the moment time object to string
return localTime;
}
php example for server side resolution (only use one of these solutions, both together will produce an incorrect time on the client end)
/**
* #param $dateTimeUTC
* #param string $timeZone
* #param string $dateFormat
* #return string
*
* epoch to datetime (utc/gmt)::
* gmdate('Y-m-d H:i:s', $epoch);
*/
function dateToTimezone($timeZone = 'UTC', $dateTimeUTC = null, $dateFormat = 'Y-m-d H:i:s'){
$dateTimeUTC = $dateTimeUTC ? $dateTimeUTC : date("Y-m-d H:i:s");
$date = new DateTime($dateTimeUTC, new DateTimeZone('UTC'));
$date->setTimeZone(new DateTimeZone($timeZone));
return $date->format($dateFormat);
}
Use function date_default_timezone_set before there you want to local time after that again setup UTC Europe/Lisbon timezone
List of Supported Timezones
<?php
$utc = "2014-05-29T04:54:30.934Z";
$time = strtotime($utc);
echo "<br/>Defualt UTC/server time".$dateInLocal = date("Y-m-d H:i:s", $time);
//your local time zone put here
date_default_timezone_set('Asia/Kolkata');
echo "<br/>Local time". $dateInLocal = date("Y-m-d H:i:s", $time);
?>
Just send the UTC time to the browser. Use JavaScript to parse it with a Date object, or with moment.js, then output it as text.
By doing it in client-side JavaScript, you don't need to be aware of the user's time zone. The browser will be responsible for that instead.
#cnvt_usrTime_to_UTC 0
function cnvt_usrTime_to_UTC($dt_start_time_formate,$UTC_TimeZone){
$LocalTime_start_time = new DateTime( $dt_start_time_formate );
$tz_start = new DateTimeZone( $UTC_TimeZone );
$LocalTime_start_time->setTimezone( $tz_start );
$array_start_time = (array) $LocalTime_start_time;
return $UTC_Time_Start_Time = $array_start_time['date'];
}
call the function
cnvt_usrTime_to_UTC($dt_start_time_formate,'UTC');
#cnvt_UTC_to_usrTime
function cnvt_UTC_to_usrTime($Date_Time,$User_time_Zone){
date_default_timezone_set('UTC');
$LocalTime_start_time = new DateTime( $Date_Time );
$tz_start = new DateTimeZone( $User_time_Zone );
$LocalTime_start_time->setTimezone( $tz_start );
$start_date_time = (array) $LocalTime_start_time;
return $StartDateTime = $start_date_time['date'];
}
call the function
cnvt_UTC_to_usrTime($value_edit['dt_start_time'],Asia/Kolkata);
try with date_default_timezone_set() and set date according timezone
date_default_timezone_set('asia/kolkata');
$utc = "2014-05-29T04:54:30.934Z";
$time = strtotime($utc);
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal; //2014-05-29 10:24:30
echo '<br>';
date_default_timezone_set('America/Chicago');
$time = strtotime($utc .' UTC');
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal; //2014-05-28 23:54:30
$savedtime = '2019-05-25 00:01:13'; //this is America/Chicago time
$servertime = ini_get('date.timezone');
$time = strtotime($savedtime . $servertime);
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal;
display value according to local timezone
2019-05-25 10:31:13 // this is Asia/Kolkata time
$utc_date = '2021-10-07T11:01:07';
//local timezone or ant timezone you want
$timezone = 'America/Los_Angeles';
$timestamp = strtotime($utc_date);
$date = new DateTime();
$date->setTimestamp($timestamp);
$date->setTimezone(new \DateTimeZone($timezone));
echo $date->format('m-d-Y g:i A') . "\n";
protected function get_timemillizone_date($timezone_id)
{
date_default_timezone_set($timezone_id);
$availdate = date('Y-m-d');
$stamp = strtotime($availdate); // get current date timestamp
$currenttimemill = $stamp * 1000;
return $currenttimemill;
}
$timezone_id = "Asia/Kolkata";
$DATA = $this->get_timemillizone_date($timezone_id);
echo $DATA;

Trouble with TimeZones in PHP

I am working on a PHP project that deal with time and dates and user timezones.
It needs to be accurate so I am storing the DateTime and a Timestamp in the DB as UTC time.
On the UI/Frontend I am trying to display the DateTimes based on a User's TimeZone.
I made this quick little demo Class below to demonstrate my current problem.
The createTimeCard() method should create a DateTime in UTC time and that seems to be working just fine.
The get12HourDateTime($date, $format = 'Y-m-d h:i:s a') method is used to display a DateTime to a user in there own Time Zone and also in 12 hour format time. Unfortunately this is where my problems begin. No matter what Time zone is set here, it always returns UTC time!
Can anyone help me figure out what I am doing wrong?
<?php
class TimeTest{
public $dateTime;
public $dateFormat = 'Y-m-d H:i:s';
public $timeZone;
public function __construct()
{
$this->timeZone = new DateTimeZone('UTC');
$this->dateTime = new DateTime(null, $this->timeZone);
}
// Create a new time card record when a User Clocks In
public function createTimeCard()
{
$dateTime = $this->dateTime;
$dateFormat = $this->dateFormat;
// Create both Timecard and timecard record tables in a Transaction
$record = array(
'clock_in_datetime' => $dateTime->format($dateFormat),
'clock_in_timestamp' => $dateTime->getTimestamp()
);
return $record;
}
// Get 12 hour time format for a DateTime string
// Simulates getting a DateTime with a USER's TimeZone'
public function get12HourDateTime($date, $format = 'Y-m-d h:i:s a')
{
$timeZone = new DateTimeZone('America/Chicago');
$date = new DateTime($date, $timeZone);
// Also tried this with no luck
$date->setTimezone(new DateTimeZone('America/Chicago'));
return $date->format($format) ;
}
}
$timeCard = new TimeTest;
$records = $timeCard->createTimeCard();
echo '<pre>';
print_r($records);
echo '</pre>';
echo $timeCard->get12HourDateTime($records['clock_in_datetime'], 'Y-m-d h:i:s a');
?>
OUTPUT
Array
(
[clock_in_datetime] => 2013-09-21 19:28:01
[clock_in_timestamp] => 1379791681
)
//This is in 12 hour format but is not in the new time zone!
2013-09-21 07:28:01 pm
DateTime says:
Note
The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. #946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).
Is this the case?
Maybe try, setTimezone():
public function get12HourDateTime($date, $format = 'Y-m-d h:i:s a')
{
$date = new DateTime($date);
$date->setTimezone(new DateTimeZone('America/Chicago'));
return $date->format($format) ;
}
EDIT
public function get12HourDateTime($date, $format = 'Y-m-d h:i:s a')
{
$date = new DateTime($date, new DateTimeZone('UTC'));
$date->setTimezone(new DateTimeZone('America/Chicago'));
return $date->format($format) ;
}
Since you first want to initialize the DateTime with the UTC timezone (since that corresponds to the $date), then shift it appropriately.
You called one constructor and that will every time assign timezone so, basically every new object created this construct is called first.
public function __construct()
{
$this->timeZone = new DateTimeZone('UTC');
$this->dateTime = new DateTime(null, $this->timeZone);
}
And when you use UNIX TIMESTAMP that will always return in the UTC time zone.

PHP 5.2.17: convert local time to GMT and GMT to local time

In my application, I just want to convert a local time to GMT and GMT to local time. I got the following two methods to do so.
function GmtTimeToLocalTime($date) {
$gmt_time = date("Y-m-d H:i:s", $date);
date_default_timezone_set("UTC");
$timestamp_in_gmt = strtotime($gmt_time);
date_default_timezone_set('Asia/Calcutta');
$local_time = date("Y-m-d H:i:s", $timestamp_in_gmt);
//date_default_timezone_set("UTC");
return $local_time;
}
function LocalTimeToGmtTime($date) {
$local_time = date("Y-m-d H:i:s", $date);
date_default_timezone_set('Asia/Calcutta');
$timestamp_in_localtime = strtotime($local_time);
date_default_timezone_set("UTC");
$gmt_time = date("Y-m-d H:i:s", $timestamp_in_localtime);
//date_default_timezone_set('Asia/Calcutta');
return $gmt_time;
}
But i got this date 1970-01-01 for all the inputs.
Please provide me the correct way.
Thanks in advance
Perhaps if you try with DateTime object you would get better result :
<?php
function GmtTimeToLocalTime($time) {
$date = new DateTime(date('Y-m-d h:i:s',$time),new DateTimezone('UTC'));
$date->setTimezone(new \DateTimezone('Asia/Calcutta'));
return $date->format("Y-m-d H:i:s");
}
A shortcut should be to look at DateTime and use DateTime::setTimezone to modify the timezone from GMT to local time, and vice-versa.
Edit: and of course, you can fill this DateTime with your timestamp using DateTime::setTimestamp or DateTime::createFromFormat.
Pass latlong in following function to get timezone.
function getTimezoneGeo($latForGeo, $lngForGeo) {
$json = file_get_contents("http://api.geonames.org/timezoneJSON?lat=".$latForGeo."&lng=".$lngForGeo."&username=demo");
$data = json_decode($json);
$tzone=$data->timezoneId;
return $tzone;
}

php convert datetime to UTC

I am in need of an easy way to convert a date time stamp to UTC (from whatever timezone the server is in) HOPEFULLY without using any libraries.
Use strtotime to generate a timestamp from the given string (interpreted as local time) and use gmdate to get it as a formatted UTC date back.
Example
As requested, here’s a simple example:
echo gmdate('d.m.Y H:i', strtotime('2012-06-28 23:55'));
Using DateTime:
$given = new DateTime("2014-12-12 14:18:00");
echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 14:18:00 Asia/Bangkok
$given->setTimezone(new DateTimeZone("UTC"));
echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 07:18:00 UTC
Try the getTimezone and setTimezone, see the example
(But this does use a Class)
UPDATE:
Without any classes you could try something like this:
$the_date = strtotime("2010-01-19 00:00:00");
echo(date_default_timezone_get() . "<br />");
echo(date("Y-d-mTG:i:sz",$the_date) . "<br />");
echo(date_default_timezone_set("UTC") . "<br />");
echo(date("Y-d-mTG:i:sz", $the_date) . "<br />");
NOTE: You might need to set the timezone back to the original as well
Do this way:
gmdate('Y-m-d H:i:s', $timestamp)
or simply
gmdate('Y-m-d H:i:s')
to get "NOW" in UTC.
Check the reference:
http://www.php.net/manual/en/function.gmdate.php
If you have a date in this format YYYY-MM-HH dd:mm:ss,
you can actually trick php by adding a UTC at the end of your "datetime string" and use strtotime to convert it.
date_default_timezone_set('Europe/Stockholm');
print date('Y-m-d H:i:s',strtotime("2009-01-01 12:00"." UTC"))."\n";
print date('Y-m-d H:i:s',strtotime("2009-06-01 12:00"." UTC"))."\n";
This will print this:
2009-01-01 13:00:00
2009-06-01 14:00:00
And as you can see it takes care of the daylight savings time problem as well.
A little strange way to solve it.... :)
Convert local time zone string to UTC string.
e.g. New Zealand Time Zone
$datetime = "2016-02-01 00:00:01";
$given = new DateTime($datetime, new DateTimeZone("Pacific/Auckland"));
$given->setTimezone(new DateTimeZone("UTC"));
$output = $given->format("Y-m-d H:i:s");
echo ($output);
NZDT: UTC+13:00
if $datetime = "2016-02-01 00:00:01", $output = "2016-01-31 11:00:01";
if $datetime = "2016-02-29 23:59:59", $output = "2016-02-29 10:59:59";
NZST: UTC+12:00
if $datetime = "2016-05-01 00:00:01", $output = "2016-04-30 12:00:01";
if $datetime = "2016-05-31 23:59:59", $output = "2016-05-31 11:59:59";
https://en.wikipedia.org/wiki/Time_in_New_Zealand
If you don't mind using PHP's DateTime class, which has been available since PHP 5.2.0, then there are several scenarios that might fit your situation:
If you have a $givenDt DateTime object that you want to convert to UTC then this will convert it to UTC:
$givenDt->setTimezone(new DateTimeZone('UTC'));
If you need the original $givenDt later, you might alternatively want to clone the given DateTime object before conversion of the cloned object:
$utcDt = clone $givenDt;
$utcDt->setTimezone(new DateTimeZone('UTC'));
If you only have a datetime string, e.g. $givenStr = '2018-12-17 10:47:12', then you first create a datetime object, and then convert it. Note this assumes that $givenStr is in PHP's configured timezone.
$utcDt = (new DateTime($givenStr))->setTimezone(new DateTimeZone('UTC'));
If the given datetime string is in some timezone different from the one in your PHP configuration, then create the datetime object by supplying the correct timezone (see the list of timezones PHP supports). In this example we assume the local timezone in Amsterdam:
$givenDt = new DateTime($givenStr, new DateTimeZone('Europe/Amsterdam'));
$givenDt->setTimezone(new DateTimeZone('UTC'));
As strtotime requires specific input format, DateTime::createFromFormat could be used (php 5.3+ is required)
// set timezone to user timezone
date_default_timezone_set($str_user_timezone);
// create date object using any given format
$date = DateTime::createFromFormat($str_user_dateformat, $str_user_datetime);
// convert given datetime to safe format for strtotime
$str_user_datetime = $date->format('Y-m-d H:i:s');
// convert to UTC
$str_UTC_datetime = gmdate($str_server_dateformat, strtotime($str_user_datetime));
// return timezone to server default
date_default_timezone_set($str_server_timezone);
I sometime use this method:
// It is not importnat what timezone your system is set to.
// Get the UTC offset in seconds:
$offset = date("Z");
// Then subtract if from your original timestamp:
$utc_time = date("Y-m-d H:i:s", strtotime($original_time." -".$offset." Seconds"));
Works all MOST of the time.
http://php.net/manual/en/function.strtotime.php or if you need to not use a string but time components instead, then http://us.php.net/manual/en/function.mktime.php
With PHP 5 or superior, you may use datetime::format function (see documentation http://us.php.net/manual/en/datetime.format.php)
echo strftime( '%e %B %Y' ,
date_create_from_format('Y-d-m G:i:s', '2012-04-05 11:55:21')->format('U')
); // 4 May 2012
try
echo date('F d Y', strtotime('2010-01-19 00:00:00'));
will output:
January 19 2010
you should change format time to see other output
General purpose normalisation function to format any timestamp from any timezone to other.
Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')
/**
* Convert Datetime from any given olsonzone to other.
* #return datetime in user specified format
*/
function datetimeconv($datetime, $from, $to)
{
try {
if ($from['localeFormat'] != 'Y-m-d H:i:s') {
$datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
}
$datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
$datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
return $datetime->format($to['localeFormat']);
} catch (\Exception $e) {
return null;
}
}
Usage:
$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta'];
$to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC'];
datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"
As an improvement on Phill Pafford's answer (I did not understand his 'Y-d-mTG:i:sz' and he suggested to revert timezone).
So I propose this (I complicated by changing the HMTL format in plain/text...):
<?php
header('content-type: text/plain;');
$my_timestamp = strtotime("2010-01-19 00:00:00");
// stores timezone
$my_timezone = date_default_timezone_get();
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date)\n";
// changes timezone
date_default_timezone_set("UTC");
echo date("Y-m-d\TH:i:s\Z", $my_timestamp)."\t\t (ISO8601 UTC date)\n";
echo date("Y-m-d H:i:s", $my_timestamp)."\t\t (your UTC date)\n";
// reverts change
date_default_timezone_set($my_timezone);
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date is back)\n";
?>
alternatively you can try this:
<?php echo (new DateTime("now", new DateTimeZone('Asia/Singapore')))->format("Y-m-d H:i:s e"); ?>
this will output :
2017-10-25 17:13:20 Asia/Singapore
you can use this inside the value attribute of a text input box if you only want to display a read-only date.
remove the 'e' if you do not wish to show your region/country.
Follow these steps to get UTC time of any timezone set in user's local system (This will be required for web applications to save different timezones to UTC):
Javascript (client-side):
var dateVar = new Date();
var offset = dateVar.getTimezoneOffset();
//getTimezoneOffset - returns the timezone difference between UTC and Local Time
document.cookie = "offset="+offset;
Php (server-side):
public function convert_utc_time($date)
{
$time_difference = isset($_COOKIE['offset'])?$_COOKIE['offset']:'';
if($time_difference != ''){
$time = strtotime($date);
$time = $time + ($time_difference*60); //minutes * 60 seconds
$date = date("Y-m-d H:i:s", $time);
} //on failure of js, default timezone is set as UTC below
return $date;
}
..
..
//in my function
$timezone = 'UTC';
$date = $this->convert_utc_time($post_date); //$post_date('Y-m-d H:i:s')
echo strtotime($date. ' '. $timezone)

Categories