Nickool
Nickool

Reputation: 3702

convert between timestamp and date time

I tried this code,it will give me the right date but the time is not correct:

function convert_datetime($str) { 

    list($date, $time) = explode(' ', $str); 
    list($year, $month, $day) = explode('-', $date); 
    list($hour, $minute) = explode(':', $time); 
    $timestamp = mktime($hour, $minute, $year, $month, $day); 
    return $timestamp; 
}  
    if(isset($_POST['submit']))
    {
    $datetime=$_POST['startdate'].' '.$_POST['start_hour'].":".$_POST['start_minute'];
    $timestamp=convert_datetime($datetime);
    echo "DateTime:".$datetime;
    echo " ";
    echo "Timestamp:".$timestamp;
    echo " ";
    $dateandtime = date("Y-m-d H:i", $timestamp);
    echo "converted:".$dateandtime;
    }

with input: 2013-1-21 21:51 I will get this out put

DateTime:2013-1-21 21:51 Timestamp:1358807073 converted:2013-01-21 22:24

so the order is not correct.and in the time part I have problem.How to fix this?

Upvotes: 2

Views: 467

Answers (3)

Matthew
Matthew

Reputation: 9949

Put in a zero field for seconds when you are passing the time. I believe it is taking 2013 seconds and using it to add 2013/60 and using it to add 33 minutes to your time. I believe that mktime assumes current date for missing fields, which is why it is still getting 2013 for the year.

Upvotes: 0

John Conde
John Conde

Reputation: 219794

Use Datetime. It's much easier and more accurate:

$datetime = DateTime::createFromFormat("Y-m-d H:i", '2013-1-21 21:51');
echo 'Timestamp: ' . $datetime->getTimestamp() . PHP_EOL;
echo 'Datetime: ' . $datetime->format("Y-m-d H:i") . PHP_EOL;

Confirmed working

Upvotes: 3

Kami
Kami

Reputation: 19407

You are missing the seconds argument - see mktime on phpdocs. In your example seconds is being supplied the value 2013, which when added to the time alters the overall result.

function convert_datetime($str) { 

    list($date, $time) = explode(' ', $str); 
    list($year, $month, $day) = explode('-', $date); 
    list($hour, $minute) = explode(':', $time); 
    $timestamp = mktime($hour, $minute, 0, $year, $month, $day); 
    return $timestamp; 
}

On a side note, php does have conversion functions built in. Try strtotime.

Upvotes: 2

Related Questions