简体   繁体   中英

Parsing a datetime string with timezone in PHP

I have a string in this format: 2013-07-31T19:20:30.45-07:00 and I want to parse it so that I can, for example, say what day of the week it is. But I'm struggling to cope with the timezone offset. If I do date_parse("2013-07-31T19:20:30.45-07:00") then I end up with something like this:

array(15) {
  ["year"]=> int(2013)
  ["month"]=> int(7)
  ["day"]=> int(31)
  ["hour"]=> int(19)
  ["minute"]=> int(20)
  ["second"]=> int(30)
  ["fraction"]=> float(0.45)
  ["warning_count"]=> int(0)
  ["warnings"]=> array(0) { }
  ["error_count"]=> int(0)
  ["errors"]=> array(0) { }
  ["is_localtime"]=> bool(true)
  ["zone_type"]=> int(1)
  ["zone"]=> int(420)
  ["is_dst"]=> bool(false)
}

It's done something with the timezone, but what do I do with 420 if I want to, for example, show information about the timezone?

In case it matters, I have previously set my default timezone using date_default_timezone_set('UTC') .

UPDATE: If the string has a positive timezone, eg 2013-07-31T19:20:30.45+07:00 then the last part of the date_parse() output is:

  ["is_localtime"]=> bool(true)
  ["zone_type"]=> int(1)
  ["zone"]=> int(-420)
  ["is_dst"]=> bool(false)
}

420 is zone in minutes.

420/60 = 7

I want to parse it so that I can, for example, say what day of the week it is.

If you want to know what day of the week it is, you have many options. For example you can use date and mktime-functions:

$parsed = date_parse("2013-07-31T19:20:30.45-07:00");
$unix_timestamp = mktime($parsed['hour'], 0, 0, $parsed['month'], $parsed['day'], $parsed['year'], (int)$parsed['is_dst']);

echo date('l', $unix_timestamp);

So you want to show the information about timezone? You can get the time zone name by using timezone_name_from_abbr function:

$name = timezone_name_from_abbr("", -1*$parsed['zone']*60, false); // NB: Offset in seconds! 
var_dump($name);

$timezone = new DateTimezone($name); 
var_dump($timezone);
2013-07-31T19:20:30.45-07:00
^ y-m-d    ^ time      ^ timezone offset

I'm guessing the timezone is -7 hours from UTC.

Keep in mind that some countries have half-hour timezones, or even minute timezones. This is probably why you get the timezone in minutes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM