开发者

Create an ISO 8601 datetime from a date and a time

I am trying to find the best way to handle creating an ISO 8601 datetime from a date that I know and a time that I know. I am dealing with UTC time when creating these datetimes and when storing them in the database. I have a date (2011-06-24) that I want to add times to, on the form I have text inputs for a start and end time. Once this form is submitted, I want to take the date that I know (2011-06-24) and the times that I know (10:00 AM and 11:30 AM) and create a datetime that will get stored for the start and end times.

I'm pretty new to working with the PHP DateTime class and this is what I came up with:

$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...

Is there a better way to do this?


How about this (see 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'), '.';

EDIT: added timezone.


$date = DateTime::createFromFormat('Y-m-d', '2011-06-24');

Adjust the arguments according to your need, depending on which arguments you're passing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜