Timezone php and angular format datetime - php

from php I write like this :
$date = new \DateTime('2019-11-15 23:00:00', new \DateTimeZone('UTC'));
$result = [
'id' => $auction->getId(),
'endDate' => $date,
];
Now in the api I saw :
endDate : 2019-11-15T23:00:00+00:00
In my linux vps when I wrote date I get :
Fri Nov 15 20:27:50 UTC 2019
The problem is that on front I have a countdown, and on every endDate is adding 2 hours and I don't understand why.

Your front will diplay the date in YOUR time zone.
In you database or backend, the date is stored with the default time zone.
Here is an example:
const date = '2019-11-15T23:00:00+00:00'
diffWithYourTimeZone = new Date(date).getTimezoneOffset();
console.log(diffWithYourTimeZone)
// You will probably see 120(min) or -120(min)
If you do console.log(new Date()) in your navigator, you will have something like this xxx xxx xx 2019 HH:MM:MiMi GMT+0200 (...) it means that you are in the zone +2H from GMT(Greenwich Mean Time). When you store data in your backend, it's always as GMT + 0. But for your user in the front, you want to dsplay their date and time. This is why your navigator convert your date in GMT + 0 in the time in GMT + 2.

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

need to store date as per user timezone in php

i have simple php script where i have this variable
$date = date('Y-m-d', time());
The Problem: The variable is storing date as per my server timezone.
What is want: I want to store date as per user time zone, take a look into
example below:
1- tom checkin from USA
2- jenne checkin from Asia
since there is 12 hrs. difference so the date will be different too sometime
here is found some example but it's not dynamic
Converting GMT time to local time using timezone offset in php
offset = '-0500';
$isDST = 1; // Daylight Saving 1 - on, 0 - off
$timezoneName = timezone_name_from_abbr('', intval($offset, 10) * 36, $isDST);
$timezone = new DateTimeZone($timezoneName);
Then you can use it in a DateTime constructor, e.g.
$datetime = new DateTime('2012-04-21 01:13:30', $timezone);
Now what exactly i am looking,
1- in case of TOM $date should be 18
11:38 PM
Tuesday, 18 April 2017 (GMT-5)
Time in Chicago, IL, USA
2- in case of jenne $date should be 19
9:40 AM
Wednesday, 19 April 2017 (GMT+5)
Time in Lahore
difficult writing code in the comments section so i posted a working answer for you here
<?php
// here $usertimezone should be set = to what you have in your database
$usertimezone="Asia/Shanghai";
date_default_timezone_set('"'.$usertimezone.'"');
//new date and time
$ndate= new datetime();
//split into date and time seperate
$nndate =$ndate->format("Y-m-d");
$nntime= $ndate->format("H:i:S");
//here you can test it
echo $nndate;
echo $nntime;
?>
Use this function date_default_timezone_set for setting timezone, From this function you can set the timezone according to user and then get the required format.
Examples
<?php
date_default_timezone_set("new/timezone");//set the name of timezone here example Asia/Kokata
echo $date= date("Y-m-d H:i:s");

Unrecognized Date format

Good !
I am having some difficulties with extracting data from a date. The thing is that I get a number from an undocumented API.
"created": 734394
"last_chapter_date": 734883
I tried dividing it by 365,242 days (exact amount of days a year)
2010,705231052289
So apparently these are the number of days passed since 0.0.0000
I am currently trying something like that:
http://jsfiddle.net/LRUy5/4/
function zero21970(nDays) {
// 0 70 2013
// |-----|-----|
// 0 to date
var dateMils = nDays*24*60*60*100;
// 0 to 1970
zeroTo1970 = (1970*365.242)*24*60*60*100;
//subtract time from 0-1970 from the time 0-date
//to cut out the part from 1970-today
return new Date(dateMils-zeroTo1970);
}
//http://www.mangaeden.com/api/manga/4e70e9f6c092255ef7004344/
zero21970(734394) //-> Jan 26 1974
I need to save it in a database and work with it via php or javascript..
Does anyone recognize this kind of format or do you know a convenient way of formatting it?
Edit: I should add that the last chapter came out around 15.01.2013.. just to have something to grab.
Updated version:
I guess if the last chapter was from 2013, then the value is a number of days from 01.01.0001. So we can update the initial date as well as change setHours to setDate method for more accuracy:
var date = new Date("0001");
date.setDate(734883);
date.toGMTString(); // "Tue, 15 Jan 2013 00:00:00 GMT"
DEMO: http://jsfiddle.net/LRUy5/6/
Old version:
I found one solution that successfully works at my computer:
var date = new Date("0000");
date.setHours(734394 * 24);
date.toGMTString(); // "Mon, 13 Sep 2010 21:00:00 GMT"
DEMO: http://jsfiddle.net/LRUy5/5/
If you're using PHP, then you should replace
return new Date(dateMils-zeroTo1970);
with
return date('Y-m-d', (dateMils-zeroTo1970));

Get time zone offset between two timezones for a given duration

I wanted to know if there is a way to get the time zone offset for a given date range between two timezones for a given duration.
getTimezoneOffset(startDate,endDate,timezone1,timezone2){
...missing magic to go here...
}
should return the time zone offset which is valid for the a given duration. However if the offset changes, it should return the date range for which it's valid.
So I am looking at something like this:
getTimezoneOFfset("march 9 12 am", "march 15 12 am", "UTC", "US/NEW_YORK")
return value something like this
timezoneoffset[0]["range"]=[march 9 12am to march 11 2 am]
timezoneoffset[0]["offset"]=5
timezoneoffset[1]["range"]=[march 9 2 am to march 15 12 am]
timezoneoffset[1]["offset"]=4
I just don't want to calculate timezone offsets for every scheduled item for the given range. Was looking if there is some way to get a direct lookup for offsets if it's going to change.
I am working with PHP, but a solution in any language will be appreciated.
MySQL solution will also work as it will be more optimized to do this in MySQL.
Assuming that you have a newer version of php (5.2.0+) the DateTimeZone class is part of the PHP core and will let you use the getOffset() function to make these calculations. It will let you pass in a dateTime object and specify a timezone. If you do this for both your dates you should be able to calculate all of the pieces you're looking to grab. To use an example from php.net:
// Create two timezone objects, one for Taipei (Taiwan) and one for
// Tokyo (Japan)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");
// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$dateTimeTaipei = new DateTime(mktime([the date in question]), $dateTimeZoneTaipei);
$dateTimeJapan = new DateTime(mktime([the date in question]), $dateTimeZoneJapan);
// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);
// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
print("Number of seconds Japan is ahead of GMT at the specific time: ");
var_dump($timeOffset);
print("<br />Number of seconds Taipei is ahead of GMT at the specific time: ");
var_dump($dateTimeZoneTaipei->getOffset($dateTimeTaipei));
print("<br />Number of seconds Japan is ahead of Taipei at the specific time: ");
var_dump($dateTimeZoneJapan->getOffset($dateTimeTaipei)
-$dateTimeZoneTaipei->getOffset($dateTimeTaipei));
This working for me:
function Get_Timezone_Offset($remote_tz, $origin_tz = null)
{
if($origin_tz === null)
{
if(!is_string($origin_tz = date_default_timezone_get())) {
return false;
}
}
$origin_dtz = new DateTimeZone($origin_tz);
$remote_dtz = new DateTimeZone($remote_tz);
$origin_dt = new DateTime("now", $origin_dtz);
$remote_dt = new DateTime("now", $remote_dtz);
$offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
return $offset;
}
To use it
echo Get_Timezone_Offset('America/New_York', 'Europe/Stockholm');
Source:
http://php.net/manual/en/function.timezone-offset-get.php
I think PHP's DateTimeZone::getTransitions method can get you there. It has a procedural alias, timezone_transitions_get().
public array DateTimeZone::getTransitions (
[ int $timestamp_begin [, int $timestamp_end ]] )
This method returns all "transitions" from one time zone offset value to another, for that timezone, in a given time range.
For your purposes, you will want to create DateTimeZone objects for each of your time zones, call DateTimeZone::getTransitions for your date range to get an array of transitions for that time zone, then merge and sort the two arrays of transitions. This will give you the equivalent of the timezoneoffset[] array you seek.
Something like:
getTimezoneOffset(startDate,endDate,timezone1,timezone2){
DT1 = DateTimeZone( timezone1 );
transitions1 = DT1->getTransitions( startDate,endDate );
DT2 = DateTimeZone( timezone2 );
transitions1 = DT2->getTransitions( startDate,endDate );
timezoneoffset[] = // merge and sort (transitions1, transitions2)
}
The format of the transitions array isn't well documented. The method documentation shows some example entries:
Array
(
...
[1] => Array
(
[ts] => -1691964000
[time] => 1916-05-21T02:00:00+0000
[offset] => 3600
[isdst] => 1
[abbr] => BST
)
[2] => Array
(
[ts] => -1680472800
[time] => 1916-10-01T02:00:00+0000
[offset] => 0
[isdst] =>
[abbr] => GMT
)
...
)
I speculate that: ts refers to a PHP timestamp in epoch seconds, as returned by time(), giving the instant in time at which the offset changes to the value in this record. time refers to the same instant, as a formatted string date-time. offset is the timezone's offset in seconds from UTC, as of the instant time/ts, forward to the next transition. isdst is 1 if the offset refers to a daylight savings time offset, 0 otherwise. abbr is a string abbreviation for the time zone. If anyone has solid information about this data structure, it would be a kindness to add it to the documentation.

How to convert datetime to GMT in php

Alright, so i'm not sure if im converting user input time to GMT properly. I will be having users across several timezones entering "events" and they will have to be able to see "how long untill" or "how long since" the current time();
This is how I was planning to convert the time they input. It will start as something like 07/21/2011 01:30 am Then,
echo gmdate('Y-m-d H:i:s',strtotime('07/21/2011 01:30 am'));
gives me 2011-07-21 08:30:00
So I was planning to take the value of gmdate('Y-m-d H:i:s',strtotime('07/21/2011 01:30 am')); then take time() and display "how long until this event" to users. But it seems like there is always 10 hours added onto the result, so if if i was scheduling an event 30 min from now it would say 10 hours 30 min from now. So, im thinking im not converting the local time correctly or something.
What am I missing? Maybe I just dont properly understand GMT. How can I make sure all the times involved are GMT so all times are universal to all the users on the website?
Other info if it helps:
The server timezone is America/Los_Angeles
EDIT:
After everyones suggestions i've tried setting this at the top of my php code:
date_default_timezone_set("GMT");
and I tried using date('Y-m-d H:i:s') to do the comparison to figure out the diff, but its saying "3 hours ago" rather than the 10 hours from now. So this definately changed things.
But still not correct.
I've confirmed date('Y-m-d H:i:s') is returning the correct and current GMT. So thats good.
But the user input date is off. How am I converting it incorrectly?
EDIT AGAIN(including some test results after Salman A's suggestions):
2:55am - my current local time EST
date('Y-m-d H:i:s') shows up as 2011-07-21 06:56:43 - which is correct
3:00am EST is the time in the future I submitted as 07/21/2011 03:00 am
Here's how I get the time "convert it" and submit it to my DB:
$time = $_POST['time'];
//there is where im assuming it turns my EST time to the GMT equivalent.
$the_date = strtotime($time . ' GMT');
$utctime = gmdate('Y-m-d H:i:s',$the_date);
I'm expecting my function to tell me the event is 5 minutes from now, but its hours off.
just to make sure the user submitted time was actually converted to GMT i display $utctime and it shows up as 2011-07-21 03:00:00 - which is not 08:00 or 07:00 (which i think one of those would be the GMT equivalent)
So how do I convert it?
So, what im seeing is strtotime($time . ' GMT'); doesn't seem to be applying the GMT to the local time I supply. On a side note: somone suggested I have date_default_timezone_set("GMT"); in my code, so i have it at the top. Should I remove it? but i noticed if i remove it the GMT is incorrect. So thats why I left it.
If you simply need to calculate the difference between two time values:
<?php
$time = '07/21/2011 11:30 am';
$timeleft = strtotime($time) - time();
// target time....: 2011-07-21 11:30:00
// current time...: 2011-07-21 11:13:45
// difference.....: 975 seconds (16 min, 15 seconds)
The above example assumes that $time has same timezone as that used by the time() function i.e. the server's timezone.
If the timezones differ, you must normalize them in order for subtraction to work as expected. So for example if you're storing GMT date/time in your database then the above example becomes:
<?php
$time = '07/21/2011 06:30 am';
$timeleft = strtotime($time . ' GMT') - time();
// target time............: 2011-07-21 06:30:00 GMT
// converted local time...: 2011-07-21 11:30:00 PKT
// current time...........: 2011-07-21 11:34:48 PKT
// difference.............: -288 seconds (minus 4 minutes, 48 seconds)
Edit 1
Regarding this code:
$time = $_POST['time'];
If your users are from various parts of the world, you should either:
ask them to enter the date/time in GMT
ask them to enter a timezone for the date entered
You can later convert the date on server side and store it in database:
<?php
$source_time = '2011-07-21 17:00';
$source_offset = '-0700'; // PDT
$local_timestamp = strtotime($source_time . ' ' . $source_offset); // 2011-07-22 05:00 PKT (SERVER TIME)
list(
$temp_hh,
$temp_mm
) = explode(':', date('P')); // returns difference between SERVER TIME and GMT
$local_offset = $temp_hh * 3600 + $temp_mm * 60;
$gmt_timestamp = $local_timestamp + $local_offset;
echo date("Y-m-d H:i:s", $gmt_timestamp); // 2011-07-21 10:00:00
// THIS is what you store in your database
// Same as 2011-07-21 17:00:00 minus 7 hours
Without the timezone information your calculations will be unreliable.
Edit #2
Actually... it is much simpler:
<?php
$source_time = '2011-07-21 17:00';
$source_offset = -7.0; // -0700
echo date("Y-m-d H:i:s", strtotime($source_time) + $source_offset * 3600);
// 2011-07-21 10:00:00
// THIS is what you store in your database
Edit #3
<input type="text" name="time" id="time" value="07/21/2011 17:00">
<input type="text" name="offset" id="offset">
<script type="text/javascript">
document.getElementById("time").onchange = function(){
var d = new Date(this.value);
alert('Date entered: ' + d + '\nDate to GMT: ' + d.toUTCString());
}
document.getElementById("offset").value = (new Date()).getTimezoneOffset() / 60;
</script>
Demo here
A good idea is to explicitly set the timezone for your scripts. For example:
date_default_timezone_set('Europe/London');
This will make all date functions returns dates in GMT, and I believe accounting for BST too.
Hello I am living in Poland and we have a CET time.
To convert CET to GMT I am using function:
function convertCETtoGMT($timeCET)
{
date_default_timezone_set('EUROPE/London');
$time = $timeCET." CET";
$timeGMT = date('Y-m-d H:i:s', strtotime($time));
date_default_timezone_set('EUROPE/Warsaw'); //set back to CET
return $timeGMT;
}

Categories