dsa88886666 2013-05-05 08:18
浏览 384
已采纳

PHP使用DateTime将日期转换为时间戳减少1天 - 很奇怪

Have the following simple PHP code:

$day = '2013-05-04';
$disp_day = DateTime::createFromFormat('U', strtotime($day));
echo $day . " " . $disp_day->format('F j');

It outputs

2013-05-04 May 3

But $disp_date should be May 4 right?

  • 写回答

1条回答 默认 最新

  • dounei5721 2013-05-05 08:24
    关注

    It's a timezone issue.

    strtotime will give you a timezone senstitive timestamp, while createFromFormat with the U parameter will interpret the timestamp as GMT.

    • I'm guessing your time zone is India (GMT + 5.5). Hence, strtotime("2013-05-04") will get you a timestamp that in India is 2013-05-04 00:00. However, in GMT, where it's five and a half hours earlier, the time is 2013-05-03 18:30.

    • You are then passing this Indian timestamp as GMT to CreateFromFormat, leading to the shift.

    There is no need to use strtotime here at all: just do

    DateTime::createFromFormat('Y-m-d', $day);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失