is there any chance to convert database utc zone timestamps record into local timezone in PHP?
//example of code
$utc_date = $row['utc_date'];
// common values
$timezone = "Australia/Melbourne";
$tz = new DateTimeZone($timezone);
$dt = new DateTime();
$dt->setTimezone($tz);
// this can run inside a loop or by itself
$utc_date = $row['utc_date'];
$dt->setTimestamp(strtotime($utc_date));
$datetime = $dt->format("Y-m-d H:i:s");
// use the formatted date as required
echo $datetime;
You can create a new DateTime object inside a loop if you prefer or create it outside the loop and reuse it.
If the date/times don't come out of the database in the format 2019-07-18 10:00:00+00:00 you may have to add +00:00 to the retreived date.
You can simple use following exmaple to resolve your problem
<?php
//Conside in UTC the date and time will be looks like this
$utcTime = time();
echo date("Y-m-d H:i:s", $utcTime);
//now change it to your time zone
date_default_timezone_set('Your-local-time-zone');
$utc_date = date("Y-m-d H:i:s", strtotime($row['utc_date']));
?>
Let Say for my time zone I'll use
date_default_timezone_set('Asia/Kolkata');
Also, You can find your timezone supported by PHP or not here
You can read more about PHP Date funcation from here
I want to get difference between 2 timestamps of format Y-m-d H:i:s in minutes in PHP.
The code used is,
$currentDate = date('Y-m-d H:i:s');
$userLastActivity = date($date);
$timeLapse = (($currentDate - $userLastActivity)/60);
Here, $date is obtained from database.
The value of $timeLapse is 0 in output. Please help.
Try using unix timestamp. Practically it measures the time in seconds from 1/1/1970 and it's a lot easier to use and understand than a php object.
$currentTimestamp = new DateTime()->getTimestamp();
$userLastActivity = date($date)->getTimestamp();
$timeLapse = (($currentDate - $userLastActivity)/60);
You should have the time saved as timestamp on the server too, in that case you could use the $date directly as a number, with no need for a conversion. And also, because it's universal, you can pass it around to javascript or any other language without any worries for conversion
Use strtotime to parse textual datetime into a Unix timestamp and substract $userLastActivity from $currentDate and divide by 60.
See if this helps -
<?php
$currentDate = strtotime(date('Y-m-d H:i:s'));
$date = "2016-10-11 02:40:50";
$userLastActivity = strtotime($date);
echo round(abs($currentDate - $userLastActivity) / 60). " minutes";
?>
For more details :strtotime
Change these 2 lines for a start, as I don't think dividing dates by 60 is gonna work to well.
$currentDate = time();
$userLastActivity = strtotime($date);
That way you have time stamps and not dates (string)
My plan:
Get the current timestamp using strtotime("now")
Convert that to timezone '0' - This is the part I don't know how to do. I have the number that represents the users timezone, like -8 hours for example.
Store it in the database in timezone '0'
Retrieve it from the database in timezone '0'
Convert it to the users timezone in the opposite direction
use the date('', timestamp) function to display it
How can I accomplish the conversion? Or am I going about this wrong?
I need to be able to store it in the database as a numerically represented time (like strtotime returns)
Using time() is the same as strtotime("now") and you do not need to worry about converting the timezone of the timestamp, as the timestamp has no timezone:
Does PHP time() return a GMT/UTC Timestamp?
time returns a UNIX timestamp, which is timezone independent. Since
a UNIX timestamp denotes the seconds since 1970 UTC you could say it's
UTC, but it really has no timezone.
You can then store that timestamp in your database. When you retrieve it you can convert it to the users timezone. With something like this:
date_default_timezone_set('UTC');
$timestamp = '1429066967';
//Supported Timezones: http://php.net/manual/en/timezones.php
$userTimezone = 'America/Los_Angeles';
$dt = new DateTime();
// Set the timestamp
$dt->setTimestamp($timestamp);
// Set the timezone
$dt->setTimezone(new DateTimeZone($userTimezone));
// Format the date
$date = $dt->format('Y-m-d H:i:s');
echo $date;
Outputs: 2015-04-14 20:02:47
But if you only have the UTC offset you could try this:
date_default_timezone_set('UTC');
$timestamp = '1429066967';
$offset = -8;
$userTimezone = timezone_name_from_abbr("", $offset*3600, false);
$dt = new DateTime();
// Set the timestamp
$dt->setTimestamp($timestamp);
// Set the timezone
$dt->setTimezone(new DateTimeZone($userTimezone));
// Format the date
$date = $dt->format('Y-m-d H:i:s');
echo $date;
Which also outputs: 2015-04-14 20:02:47
I want to store the expiration time in database. I am using the below code to store expiration time with +1 year.
$cdate = time();
$date = $cdate + 365*24*60*60;
$date = date("Y-m-d H:i:s",$date);
but its not storing the correct time it stores 2014-08-10 07:55:14 but time on storing is 2014-08-10 01:25:14.
Aslo not sure its Am or Pm .
Thanks.
Time/date functions in PHP are using timezones to determine your local time. So if your server is in timezone GMT+6 that means that the date() function will return you the date/time that is 6 hours before GMT.
You can check the date_default_timezone_set() function manual to find out how PHP is selecting your timezone.
To set your timezone, you can use date_default_timezone_set() before calling date function or you can set you php.ini setting date.timezone to your timezone.
For the second part of your question - when formatting time using the date() function the H format character will return 24-hour format of an hour with leading zeros.
try this
<?php
$timezone1 = "America/Los_Angeles";
date_default_timezone_set($timezone1);
$cdate = time();
$date1 = $cdate + 365*24*60*60;
$date = date("Y-m-d H:i:s a",$date1);
echo $date;
$timezone = "Asia/Calcutta";
date_default_timezone_set($timezone);
$cdate = time();
$date1 = $cdate + 365*24*60*60;
$date = date("Y-m-d H:i:s a",$date1);
echo $date;
?>
you can set timezone for your location.And also refer this codepad-FIDDLE
As others have mentioned, it is calculating the time based on your server (local) time.
I suggest you store the time in GMT and then adjust it to your desired timezone as necessary.
You can use strtotime() to calculate 1 year from now (no need to calculate it yourself) and use gmdate() to get the timestamp in GMT.
echo "Next Year in local time: ". date("Y-m-d H:i:s", strtotime("+1 year")) ."\n";
echo "Next year in GMT: " . gmdate ("Y-m-d H:i:s", strtotime ("+1 year")) . "\n";
// Output:
// Next Year in local time: 2014-08-10 15:25:09
// Next year in GMT: 2014-08-10 08:25:09
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)