【问题标题】:Create an ISO 8601 datetime from a date and a time从日期和时间创建 ISO 8601 日期时间
【发布时间】:2011-06-23 13:26:51
【问题描述】:

我正在尝试找到从我知道的日期和我知道的时间创建 ISO 8601 日期时间的最佳方法。在创建这些日期时间并将它们存储在数据库中时,我正在处理 UTC 时间。我有一个日期(2011-06-24),我想在表格上添加时间,我有开始和结束时间的文本输入。提交此表单后,我想获取我知道的日期(2011-06-24)和我知道的时间(上午 10:00 和上午 11:30),并创建一个将存储的日期时间开始和结束时间。

我对使用 PHP DateTime 类很陌生,这就是我想出的:

$day = "2011-06-24";
$start = "10:00 AM";
$end = "11:30 AM";

$date = new DateTime();
$date->setTimestamp(strtotime($start));
$date->setDate(date('Y', strtotime($day)), date('m', strtotime($day)), date('d', strtotime($day)));

// same for $end...

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: php datetime


    【解决方案1】:

    这个怎么样(见DateTime documentation):

        <?php
    
        $day = "2011-06-24";
        $start = "10:00 AM";
        $end = "11:00 AM";
    
        $startdate = DateTime::createFromFormat('Y-m-d g:i A', $day.' '.$start, new DateTimeZone('UTC'));
        $enddate = DateTime::createFromFormat('Y-m-d g:i A', $day.' '.$end, new DateTimeZone('UTC'));
        //date('c') generates ISO 8601 formatted date
        echo 'From ', $startdate->format('c'), ' to ', $enddate->format('c'), '.';
    

    编辑:添加时区。

    【讨论】:

      【解决方案2】:
      $date = DateTime::createFromFormat('Y-m-d', '2011-06-24');
      

      根据您的需要调整参数,具体取决于您传递的参数。

      【讨论】:

        猜你喜欢
        • 2010-10-23
        • 1970-01-01
        • 1970-01-01
        • 2022-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多