【发布时间】:2019-07-03 13:14:03
【问题描述】:
我想查找日期是否为“j/n/Y”格式,如果是,那么我想将 ot 转换为“d/m/Y”。如果它已经是“d/m/Y”格式,我不想对其进行任何更改。
我试过了-
$date = '1/7/2019';
这里我假设 1 作为日期,7 作为月份,2019 作为年份(显然)。现在,
$date_format_changed = date("d/m/Y", strtotime($date));
上面的代码给我的输出是“07/01/2019”。但我希望输出为“01/07/2019”。
如果日期已经是 d/m/Y 格式,例如 2019 年 12 月 17 日,当这个字符串将在上面的日期转换代码中传递时,它会给我输出“01/01/1970”。不知道为什么。
请帮忙!
【问题讨论】:
-
这将很难检查。 2019 年 1 月 7 日的有效期为 7 月 1 日和 1 月 7 日。大于 12 天会更容易,但小于 12 天会很不稳定。
-
strtotime 的注释说
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d. -
如果您知道字符串总是
j/n/Y或d/m/Y,那么您可以检查长度。如果日期字符串的长度是 8 或 9,那么它就是j/n/Y。如果长度为10,则为d/m/Y。