dragonlew9876 2012-08-01 05:08
浏览 60
已采纳

PHP strtotime EST来回转换

For EST time, I've set:

date_default_timezone_set("America/New_York");

As the page loads, I'm getting EST time via:

$time = time();

The problem is when I convert strings back and forth between timestamps and datetime format:

10/31/2012 7:30pm 1351729800 | 10/31/2012, 8:30 pm
11/2/2012 7:30pm 1351902600 | 11/02/2012, 8:30 pm
11/3/2012 8:00pm 1351990800 | 11/03/2012, 9:00 pm
11/7/2012 8:00pm 1352336400 | 11/07/2012, 8:00 pm
11/9/2012 8:00pm 1352509200 | 11/09/2012, 8:00 pm
11/10/2012 8:00pm 1352595600 | 11/10/2012, 8:00 pm

I'm expecting these date & times to be the same.

The first section (before the "|") is simply strings, such as "10/31/2012 7:30pm" and the strtotime("10/31/2012 7:30pm EST").

The section (after the "|") is date() of the previous strtotime() value.

What can I do to convert from string to time (strtotime) and double check that the date format returned is the same as the string input?

Thanks

  • 写回答

2条回答 默认 最新

  • duanchongzi9997 2012-08-01 05:46
    关注

    I'd say that this is because currently New York is on daylight savings time - EDT rather than EST. This affects things like so:

    date_default_timezone_set("America/New_York");
    strtotime("10/31/2012 7:30pm"); // translates to "Wed, 31 Oct 2012 19:30:00 -0400"
    strtotime("10/31/2012 7:30pm EDT"); // translates to "Wed, 31 Oct 2012 19:30:00 -0400"
    strtotime("10/31/2012 7:30pm EST"); // translates to "Wed, 31 Oct 2012 20:30:00 -0400"
    

    The quick fix is probably to not add the timezone to the string, strtotime() will use the correct default timezone you set.

    You can be a bit more exact about how your date is being parsed by using the DateTime createFromFormat function:

    $date = DateTime::createFromFormat('m/d/Y g:ia', "10/31/2012 7:30pm");
    echo $date->format('U');
    

    Alternatively if you wait until November the problem will resolve itself :-)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题