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 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序