【问题标题】:How to check whether a date is in j-n-Y format or not? if yes then how to convert it to d-m-Y format? [duplicate]如何检查日期是否为 j-n-Y 格式?如果是,那么如何将其转换为 d-m-Y 格式? [复制]
【发布时间】: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/Yd/m/Y,那么您可以检查长度。如果日期字符串的长度是 8 或 9,那么它就是 j/n/Y。如果长度为10,则为d/m/Y

标签: php date strtotime


【解决方案1】:

一种方法可以是将explode的日期转化为它的日月年分量,然后对其进行分析

$date = '1/7/2019'; 

$array = explode("/", $date);

$day = $array[0];
$month = $array[1];
$year = $array[2];

if(strlen($day) == 1) $day = "0".$day;
if(strlen($month) == 1) $month = "0".$month;

echo $day."/".$month."/".$year;

【讨论】:

  • 你可以简单地做一个strlen($date)。如果长度为 8 或 9,则为 j/n/Y,如果为 10,则为 d/m/Y
  • @MagnusEriksson- 是的,我们可以这样做,但是我们仍然需要分解 $date 变量以将 0 与日期和月份连接起来,以便我们可以实现 d-m-Y 格式的日期。
【解决方案2】:

您可以“帮助”解释器猜出正确的格式。

date_create_from_format 是一种方法。

$date = '1/7/2019';
$parsed = date_create_from_format("j/n/Y", $date);

if ($parsed == false) {
    // Not in j/n/Y format
} else {
    $dmY = $parsed->format("d/m/Y");
}

请注意,这还将解析理论上与 j/n/Y 匹配但以不同方式设计的日期。 (例如,当您使用 d/m/Y 时,它也可能检测到 m/d/Y)

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2012-07-21
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多