简体   繁体   English

将月份,年份转换为Y​​YYY-MM-DD

[英]Convert Month, Year to YYYY-MM-DD

I wrote some code last year that search to and from taking in dates like 'January, 2018' and converting it to the first day of the month. 去年我写了一些代码来查找和接收诸如“ January,2018”之类的日期,并将其转换为该月的第一天。 I have now found there to be a bug and my code is now return the current year, not the searched year. 我现在发现有一个错误,并且我的代码现在返回当前年份,而不是搜索的年份。

$From = "January, 2018";
$From = strtotime($From);
$From = date('Y-m-01', $From);

This returns this: 2019-01-01 when I want 2018-01-01 这将返回此:2019-01-01当我想要2018-01-01时

Any suggestions on how to fix this? 对于如何解决这个问题,有任何的建议吗?

Your date string is missing the day, so you could add the day yourself and specify the format it is in right now to create a date object. 您的日期字符串缺少日期,因此您可以自己添加日期并指定当前格式以创建日期对象。 Then you can display that date object in whatever format you want: 然后,您可以使用任何所需的格式显示该日期对象:

$From = "January, 2018";
$From = DateTime::createFromFormat('d, M, Y','1,'.$From);
$From = $From->format('Y-m-d');
// Outputs 2018-01-01

Read more about createFromFormat here: http://php.net/manual/en/datetime.createfromformat.php 在此处阅读有关createFromFormat的更多信息: http ://php.net/manual/en/datetime.createfromformat.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM