在 PHP 中转换日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2487921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:40:36  来源:igfitidea点击:

Convert a date format in PHP

phpdateformatting

提问by matthy

I am trying to convert a date from yyyy-mm-ddto dd-mm-yyyy(but not in SQL); however I don't know how the date function requires a timestamp, and I can't get a timestamp from this string.

我正在尝试将日期从 转换yyyy-mm-dddd-mm-yyyy(但不是在 SQL 中);但是我不知道 date 函数如何需要时间戳,而且我无法从这个字符串中获取时间戳。

How is this possible?

这怎么可能?

回答by richsage

Use strtotime()and date():

使用strtotime()date()

$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));

(See the strtotimeand datedocumentation on the PHP site.)

(请参阅PHP 站点上的strtotimedate文档。)

Note that this was a quick solution to the original question. For more extensive conversions, you should really be using the DateTimeclass to parse and format :-)

请注意,这是对原始问题的快速解决方案。对于更广泛的转换,您应该真正使用DateTime该类来解析和格式化:-)

回答by ceiroa

If you'd like to avoid the strtotime conversion (for example, strtotime is not being able to parse your input) you can use,

如果您想避免 strtotime 转换(例如, strtotime 无法解析您的输入),您可以使用,

$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('d-m-Y');

Or, equivalently:

或者,等效地:

$newDateString = date_format(date_create_from_format('Y-m-d', $dateString), 'd-m-Y');

You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.

你首先给它 $dateString 的格式。然后你告诉它你想要 $newDateString 的格式。

Or if the source-format always is "Y-m-d" (yyyy-mm-dd), then just use DateTime:

或者,如果源格式始终为“Ymd”(yyyy-mm-dd),则只需使用DateTime

<?php
    $source = '2012-07-31';
    $date = new DateTime($source);
    echo $date->format('d.m.Y'); // 31.07.2012
    echo $date->format('d-m-Y'); // 31-07-2012
?>

回答by Tim Lytle

Use:

用:

implode('-', array_reverse(explode('-', $date)));

Without the date conversion overhead, I am not sure it'll matter much.

如果没有日期转换开销,我不确定它会很重要。

回答by Alper Sar?

$newDate = preg_replace("/(\d+)\D+(\d+)\D+(\d+)/","--",$originalDate);

This code works for every date format.

此代码适用于每种日期格式。

You can change the order of replacement variables such $3-$1-$2 due to your old date format.

由于您的旧日期格式,您可以更改替换变量的顺序,例如 $3-$1-$2。

回答by Kevin

$timestamp = strtotime(your date variable); 
$new_date = date('d-m-Y', $timestamp);

For more, see the documentation for strtotime.

如需更多信息,请参阅有关文档strtotime

Or even shorter:

或者更短:

$new_date = date('d-m-Y', strtotime(your date variable));

回答by Gabriel

Also another obscure possibility:

还有另一种不为人知的可能性:

$oldDate = '2010-03-20'
$arr = explode('-', $oldDate);
$newDate = $arr[2].'-'.$arr[1].'-'.$arr[0];

I don't know if I would use it but still :)

我不知道我是否会使用它,但仍然:)

回答by Igor Donin

Note: Because this post's answer sometimes gets upvoted, I came back here to kindly ask people not to upvote it anymore. My answer is ancient, not technically correct, and there are several better approaches right here. I'm only keeping it here for historical purposes.

Although the documentation poorly describes the strtotime function, @rjmunro correctly addressed the issue in his comment: it's in ISO format date "YYYY-MM-DD".

Also, even though my Date_Converter function might still work, I'd like to warn that there may be imprecise statements below, so please do disregard them.

注意:因为这篇文章的答案有时会被点赞,所以我回到这里恳请人们不要再点赞了。我的答案很古老,技术上不正确,这里有几种更好的方法。我只是出于历史目的将它保留在这里。

尽管文档对 strtotime 函数的描述很差,@rjmunro 在他的评论中正确地解决了这个问题:它是 ISO 格式的日期“YYYY-MM-DD”。

另外,即使我的 Date_Converter 函数可能仍然有效,我想警告一下,下面可能有不准确的陈述,所以请忽略它们。

The most voted answer is actually incorrect!

得票最多的答案实际上是错误的!

The PHP strtotime manual herestates that "The function expects to be given a string containing an English date format". What it actually means is that it expects an American US date format, such as "m-d-Y" or "m/d/Y".

此处的 PHP strtotime 手册指出“该函数期望得到一个包含英文日期格式的字符串”。它的实际意思是它需要一个美国的美国日期格式,例如“mdY”或“m/d/Y”。

That means that a date provided as "Y-m-d" may get misinterpreted by strtotime. You should provide the date in the expected format.

这意味着提供为“Ymd”的日期可能会被strtotime. 您应该以预期的格式提供日期。

I wrote a little function to return dates in several formats. Use and modify at will. If anyone does turn that into a class, I'd be glad if that would be shared.

我写了一个小函数来以多种格式返回日期。随意使用和修改。如果有人确实把它变成了一个类,我会很高兴分享。

function Date_Converter($date, $locale = "br") {

    # Exception
    if (is_null($date))
        $date = date("m/d/Y H:i:s");

    # Let's go ahead and get a string date in case we've
    # been given a Unix Time Stamp
    if ($locale == "unix")
        $date = date("m/d/Y H:i:s", $date);

    # Separate Date from Time
    $date = explode(" ", $date);

    if ($locale == "br") {
        # Separate d/m/Y from Date
        $date[0] = explode("/", $date[0]);
        # Rearrange Date into m/d/Y
        $date[0] = $date[0][1] . "/" . $date[0][0] . "/" . $date[0][2];
    }

    # Return date in all formats
        # US
        $Return["datetime"]["us"] = implode(" ", $date);
        $Return["date"]["us"]     = $date[0];

        # Universal
        $Return["time"]           = $date[1];
        $Return["unix_datetime"]  = strtotime($Return["datetime"]["us"]);
        $Return["unix_date"]      = strtotime($Return["date"]["us"]);
        $Return["getdate"]        = getdate($Return["unix_datetime"]);

        # BR
        $Return["datetime"]["br"] = date("d/m/Y H:i:s", $Return["unix_datetime"]);
        $Return["date"]["br"]     = date("d/m/Y", $Return["unix_date"]);

    # Return
    return $Return;

} # End Function

回答by Raja Ram T

There are two ways to implement this:

有两种方法可以实现这一点:

1.

1.

    $date = strtotime(date);
    $new_date = date('d-m-Y', $date);

2.

2.

    $cls_date = new DateTime($date);
    echo $cls_date->format('d-m-Y');

回答by Sinan

You can try the strftime()function. Simple example: strftime($time, '%d %m %Y');

你可以试试这个strftime()功能。简单的例子:strftime($time, '%d %m %Y');

回答by Juancho Ramone

Use this function to convert from any format to any format

使用此函数从任何格式转换为任何格式

function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
    $date_aux = date_create_from_format($from_format, $date);
    return date_format($date_aux,$to_format);
}