在PHP中,获取日期、比较日期、获取小时的最佳函数是什么


What is the best function to get Date, compare Date, get hour I should use in PHP

我创建了一个有产品的在线商店,我想让系统获得用户发布产品的时间和日期,并将时间存储到数据库中,我还想根据他们的输入时间显示产品。

所以我的问题是:在php中,获取日期、比较日期、获取小时的最佳函数是什么?

我从网上得到一些建议,我应该用time()来获得第二个,并将其转换为

这是处理的简单代码

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
            function secondToYear($sec){
                $year = $sec * 0.0000000316887646;
                return $year;
            }
            function secondToMonth($sec){
                $month = $sec * 0.000000380265176;
                return $month;
            }
            function secondToDay($sec){
                $day = $sec * 0.0000115740741;
                return $day;
            }
            $second = time();
            echo "second : ".$second;//in second
            ?>
            <br>
            <?php
            echo "year : ".  secondToYear($second);
            ?>
            <br>
            <?php
            echo "month : ".  secondToMonth($second);
            ?>
            <br>
            <?php
            echo "days : ". secondToDay($second);
            ?>
    </body>
</html>

我从谷歌得到了这个公式,但当我将结果与这个结果进行比较时,它与不匹配

基本:

// Current time
echo date("Y-m-d", time());
// 2013-12-01
echo date("Y-m-d", 1385925192);

--

以格式输出日期DateTime对象有一个日期值,您可以使用format()方法输出该值,并指定返回的格式。

echo $date->format('Y-m-d');

输出时间戳如果您想将DateTime值输出为时间戳,您将使用getTimestamp()方法。

$date = new DateTime();
echo $date->getTimestamp();

更改日期要更改对象的日期,您将使用setDate()方法。

$date = new DateTime();
// Outputs 2001-02-03
$date->setDate(2001, 2, 3);
echo $date->format('Y-m-d');

比较两个日期

$date1 = new DateTime('May 13th, 1986');
$date2 = new DateTime('October 28th, 1989');
$difference = $date1->diff($date2);

检查此项:http://www.paulund.co.uk/datetime-php

和php.net手册:http://php.net/manual/en/class.datetime.php

看看DateTime类及其伴随类(DateTimeZoneDateInterval)。95%的日期和时间处理都需要它们。

从传统PHP日期列表&时间函数,看看strtotime()(它解析时间的英语表示并生成时间戳值)、strftime()(如果您需要用英语以外的其他语言表示日期;它与setlocale()一起工作)和time()(如果您出于任何数字目的需要当前时间戳,如将其用作伪随机数)。大多数其他函数在通常的PHP应用程序中都不需要,或者它们的功能是由DateTime类及其朋友提供的。