简体   繁体   中英

How Do I convert datetime-local input to unix timestamp?

I am working with an input which type is datetime-local . I need to convert this to unix timestamp.

here's an example of what format the raw value submitted is 2018-06-12T19:30 .

I need to convert dates in formats such as the above into this format 1608954764 , the current unix timestamp.

strtotime() will return a Unix epoch for the time given.

<?php
strtotime("2018-06-12T19:30");
?>

You may use date_create_from_format.

date_create_from_format has the advantage to avoid system detecting wrong month and day (eg 2011-3-10 may mean 10 March or 3 Oct in different countries, but date_create_from_format is safe, it converts according to the rule you set)

As follows:

<?php
$date = date_create_from_format('Y-m-j H:i', str_replace('T',' ', '2018-06-12T19:30'));

echo $date->getTimestamp();
?>

strtotime() is the easiest choice, but you really should consider using the DateTime class whenever possible.

To get the UNIX timestamp with DateTime simply use format('U') .

// returns UNIX timestamp as string
$ts = (new DateTime("2018-06-12T19:30"))->format('U');

There is also a shortcut for this called getTimestamp() .

// returns UNIX timestamp as int
$ts = (new DateTime("2018-06-12T19:30"))->getTimestamp();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM