从php中的日期时间获取年/月/日?


72

我曾经date('w', timestamp)date('w', timestamp)认识的日子,date('n', timestamp)几个月,等等。

现在,我正在使用日期时间,我想知道从日期时间获取一天,一个月等的等效函数是什么。

PS:我知道我可以UNIX_TIMESTAMP()在SQL查询中使用,但我更喜欢避免在代码中使用时间戳。


1
您是说您正在使用php的DateTime类吗?datetime结果上的strtotime()应该给您一个时间戳,以便在其上使用date()。
Paul S.

Answers:


112

使用DateTimeDateTime :: format()

$datetime = new DateTime($dateTimeString);
echo $datetime->format('w');

50
PHP中的另一个错误设计!为什么没有函数getDay(),getMonth(),getYear()等?还是返回像getdate()这样的Array的函数呢?我不得不使用这些甚至不直观的神秘字符真是可惜。(今天,逻辑在哪里?)PHP的设计失误如此之多。使用PHP真的很丑。
Elmue

29
@Elmue有很多事情可以归咎于PHP,您可以继续这样做。或者您可以接受,它是从C. open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf(搜索strftime)中以1:1提取的。您想知道为什么“ w”是指工作日吗?奇怪。最后(90%),您通常不只希望月或日,而只需要格式化的,与语言环境相关的日期字符串。format无论如何,您将结束。
KingCrunch '17

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.