如何获取 PHP 中日期的输出

How to get the output for date in PHP

我确实在 javascript 中编写了这个脚本来获取日期输出。现在我已经将后台脚本更改为 PHP 我需要代码来获取以下格式的日期。

我也尝试获取日期,但获取的是前一天而不是当前日期。

Date.prototype.toFormattedString = function (f)

{
    var nm = this.getMonthName();
    var nd = this.getDayName();
    f = f.replace(/yyyy/g, this.getFullYear());
    f = f.replace(/yy/g, String(this.getFullYear()).substr(2,2));
    f = f.replace(/MMM/g, nm.substr(0,3).toUpperCase());
    f = f.replace(/Mmm/g, nm.substr(0,3));
    f = f.replace(/MM\*/g, nm.toUpperCase());
    f = f.replace(/Mm\*/g, nm);
    f = f.replace(/mm/g, String(this.getUTCMonth()+1).padLeft('0',2));
    f = f.replace(/DDD/g, nd.substr(0,3).toUpperCase());
    f = f.replace(/Ddd/g, nd.substr(0,3));
    f = f.replace(/DD\*/g, nd.toUpperCase());
    f = f.replace(/Dd\*/g, nd);
    f = f.replace(/dd/g, String(this.getUTCDate()).padLeft('0',2));
    f = f.replace(/d\*/g, this.getUTCDate());
    return f;
};

Date.prototype.getMonthName = function ()
{
    return this.toLocaleString().replace(/[^a-z]/gi,'');
};


Date.prototype.getDayName = function ()
{
    switch(this.getDay())
    {
        case 0: return 'Sunday';
        case 1: return 'Monday';
        case 2: return 'Tuesday';
        case 3: return 'Wednesday';
        case 4: return 'Thursday';
        case 5: return 'Friday';
        case 6: return 'Saturday';
    }
};

String.prototype.padLeft = function (value, size) 
{
    var x = this;
    while (x.length < size) {x = value + x;}
    return x;
};


var now = (new Date()).toFormattedString('yyyymmdd')

我需要像 20150221

这样的输出
$now = new DateTime()->format('Ymd');

阅读有关 DateTime class and date 函数的 PHP 文档。

像这样使用日期:

<?php

$current_day = date('Ymd');
echo $current_day;

?>

您可以在

中找到更多选项

http://php.net/manual/en/function.date.php

只需添加以下代码即可获取 PHP

中的日期
<?php
   echo date('Ymd');
?>

编辑:格式为 20150221

你也可以尝试使用 Carbon,它真的很简单,它使开发更容易,你可以在这里查看 https://github.com/briannesbitt/carbon

这是碳的用法示例

<?php
printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver'));  //implicit __toString()
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();

文档解释的很详细,没那么难。

本地系统日期:

如果您的脚本需要本地系统的日期,即通过浏览器使用您的应用程序的人的系统,那么您应该选择 JavaScript 日期而不是 PHP。在这种情况下,系统日期可能会有所不同,因为用户将从不同的区域访问它。此外,他们还可以调整系统日期。

var date = new Date();
var time = date.getTime(); //output e.g. 1424497935248

服务器系统日期:

如果您的脚本需要服务器日期,而不考虑本地系统的日期,那么您应该选择 PHP 日期。

echo date("Y-m-d h:i:sa"); //sample output 2015-02-21 06:00:15am
echo time(); //sample output 1424498415