【问题标题】:How to display the time in this format?如何以这种格式显示时间?
【发布时间】:2019-11-09 07:44:10
【问题描述】:

时间应该像0000:00:0:00:00这样显示给用户,代表YYYY:WW:D:HH:MM。我需要增加/减少/设置时间的方法。

如何使用 PHP DateTime() 来实现这一点?它应该始终以这种格式显示,即使我只有一小时也应该像这样显示0000:00:0:01:00

感谢您的帮助!

【问题讨论】:

  • 您的问题很清楚,但下面答案的 cmets 似乎毕竟问题并不清楚。使用一些示例编辑您的问题。输入应该是什么,输出应该是什么?
  • 究竟是什么不清楚?
  • 阅读我的问题,而不仅仅是第一句话。
  • 如明确所述,我从0000:00:0:00:00 开始,我需要编辑时间的函数,并且输出应始终采用这种格式,例如0000:00:0:01:00 一天。

标签: php date datetime time week-number


【解决方案1】:

试试这个:

echo date('Y:m:j:h:i');

https://www.php.net/manual/en/function.date.php 日期的第二个参数是时间戳

【讨论】:

  • 但是如果我将年份减少到 1,我怎么能在 1 前面还有 3 位数字?
  • 它将打印 0001 年
  • 我试过这个$date = new DateTime('2019-45-09 12:07'); echo $date->format('Y:w:d H:i');,我得到一个致命错误。
  • 因为你给构造函数的日期 2019-45-09 45 个月不存在
  • $date = new DateTime('2019-05-09 12:07'); echo $date->format('Y:m:j:h:i');
【解决方案2】:

echo date('Y:W:j:H:i'); PHP Manual date 做吧

Y   A full numeric representation of a year, 4 digits           Examples: 1999 or 2003
W   ISO-8601 week number of year, weeks starting on Monday      Example: 42 (the 42nd week in the year)
m   Numeric representation of a month, with leading zeros       01 through 12
j   Day of the month without leading zeros                      1 to 31
H   24-hour format of an hour with leading zeros                00 through 23
i   Minutes with leading zeros                                  00 to 59

有关您的问题,请参阅How to create datetime from week number 这是Demo

$str = '2019-45-09 12:07';
$arr = explode(" ",$str);
$date_arr = explode("-",$arr[0]);
$time_arr = explode(":",$arr[1]);
$date = new DateTime();
$date->setISODate($date_arr[0],$date_arr[1],$date_arr[2])->setTime($time_arr[0],$time_arr[1]);
echo $date->format("Y-W-d H:i:s") . PHP_EOL;
$date->add(new DateInterval("P1D"));
echo $date->format("Y-W-d H:i:s");

【讨论】:

  • 星期在哪里?
  • 另外,我该如何修改该值?
  • 修改什么值?
  • 之后我需要一种修改日期的方法。
  • 我尝试使用 DateTime() 但它弄乱了格式。请参阅我对另一个答案的评论。
猜你喜欢
  • 1970-01-01
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多