php date 如何自定义时间格式(setTime(0,0,0)或者setTime(23,59,59))

有时候获取到的时间只有年月日而没有时分秒

比如20141124.

如何更方便的设置时分秒呢,用new DateTime()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
// You time as Unix timestamp
$now = strtotime('20141124');

$d = new DateTime();

// Whenever doing date calculations, timezone is important. Set it to UTC if you don't care.
$d->setTimeZone(new DateTimeZone('America/Detroit'));

// Initialize date ( - but remember, DateTime can take many other forms of date input)
$d->setTimeStamp($now);

// Increase date by 1 month.
$d->add(new DateInterval('P1M'));

// Overwrite the "clock" part of the date
$d->setTime(0, 0, 0);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(23, 59, 59);
echo $date->format('Y-m-d H:i:s') . "\n";
// Display the result:
2014-11-24 00:00:00
2014-11-24 23:59:59

 

坚持原创技术分享,您的支持将鼓励我继续创作!