nuthan
nuthan

Reputation: 465

convert datetime to timestamp php

My GPS device is communicating to my php web services, it sends date=311011 and time=060904 formats.

    $time=str_split($time,2);
    $date=str_split($date,2);
    $time=implode(":",$time);
    $date=implode("-",$date);

This gives me the required date and time standard notations.

Now, i wanna convert this date, time to timestamp. I worked with strtotime(), but the date seems to be 31-10-11, which gives strange results. Do i have to append 20 to 11 statically to make it 2011, or any solution

Upvotes: 3

Views: 11565

Answers (3)

deceze
deceze

Reputation: 521995

You can use strptime:

$p = strptime($date.$time, '%d%m%y%H%M%S');
$timestamp = mktime($p['tm_hour'], $p['tm_min'], $p['tm_sec'], $p['tm_mon'], $p['tm_mday'], $p['tm_year']);

Or the newer DateTime variant:

$dateTime = DateTime::createFromFormat($date.$time, 'dmyHis');
$timestamp = $dateTime->format('U');

Or just string manipulation together with mktime on such a regular format:

list($d, $m, $y, $h, $i, $s) = str_split($date.$time, 2);
$timestamp = mktime($h, $i, $s, $m, $d, $y);

Upvotes: 0

oezi
oezi

Reputation: 51797

take a look at the date fortmats. if you use - as separator, php assumes it's y-mm-dd, but your order is dd-mm-y. the easiest way would be to change the separator to . wich would then be dd.mm.y.

Upvotes: 3

Ariel
Ariel

Reputation: 26753

Use strptime()

Specifically: strptime("$date $time", '%d%m%y %H%M%S');

Upvotes: 0

Related Questions