dongxiaolin2801 2010-10-21 16:07
浏览 65
已采纳

PHP DateTime不一致? 我错过了什么?

Using PHP 5.2.5 I was working with some DateTime objects and noticed a time that seemed off. The problem I'm having may be related to timezones, but I'm not sure - I'm creating a DateTime from a Unix Time Stamp and getting different/unexpected results depending on how I output it.

I created the following to easily illustrate the "issue":

$timezone = new DateTimeZone('America/Chicago'); 
$now = time(); 
$now_datetime = new DateTime('@' . $now, $timezone); 
echo phpversion() . "

"; 
echo $now . "
"; 
echo $now_datetime->format('U') . "

"; 
echo date('g:i:sa', $now) . "
";
echo $now_datetime->format('g:i:sa') . "

";

This outputs the following:

5.2.5

1287676530
1287676530

10:55:30am
3:55:30pm

I'm currently in the correct timezone, and the server shows the "right" time (10am) when using the date() function to output a formatted date, as well as 'America/Chicago' being the default timezone on that machine. But, when outputting values via DateTime::format(), the times are very different.

I added the ->format('U') just to verify that it was holding the correct timestamp.

So, I'm probably doing something wrong or I have the wrong expectations. So what am I missing?

It seems like a timezone issue with DateTime, but if that's the case, why does it show "now" in America/Chicago as ... wrong?

  • 写回答

2条回答 默认 最新

  • dongtanghuan1885 2010-10-21 16:19
    关注

    The timezone you 'insert' into DateTime is the timezone of the string, which may not be your current timezone, so PHP can calculate the actual datetime, not the timezone it uses to format your output. If you want it to output the time in a specific timezone, use $now_datetime->setTimezone($timezone).

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

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题