Datetime To Unix timestamp

前端 未结 6 1612
长发绾君心
长发绾君心 2020-12-10 12:22

Is there anyone sitting on a PHP function to convert a date of format 0000-00-00 00:00:00(datetimesql) to unix timestamp?

相关标签:
6条回答
  • 2020-12-10 12:47

    I have a solution for you right here:

    /* From MySQL datetime to Unix Timestamp 2003-12-30 23:30:59 -> 1072834230 */
    function convertMysqlDateTimeToUnixTimeStamp($date) {
        $yr=strval(substr($date,0,4));
        $mo=strval(substr($date,5,2));
        $da=strval(substr($date,8,2));
        $hr=strval(substr($date,11,2));
        $mi=strval(substr($date,14,2));
        $se=strval(substr($date,17,2));
        return mktime($hr,$mi,$se,$mo,$da,$yr);
    }
    
    0 讨论(0)
  • 2020-12-10 12:50

    To do this in PHP 5.2 you can do this:

    $datetime = new DateTime();
    echo $datetime->format('U');
    

    A newer way to do this as of PHP 5.3 is:

    $datetime = new DateTime();
    echo $datetime->getTimestamp();
    
    0 讨论(0)
  • 2020-12-10 12:50

    Another option as you have tagged this question with SQL: the MySQL functions FROM_UNIXTIME and UNIX_TIMESTAMP -> MySQL manual

    SELECT UNIX_TIMESTAMP(datetime_column) FROM table
    

    This usually is faster than a PHP function call.

    0 讨论(0)
  • 2020-12-10 12:59

    @bartek - As you noted, PHP's strtotime function is perfect for this. It can handle most common date formats, including strings like "tomorrow" or "+5 months".

    0 讨论(0)
  • 2020-12-10 13:00

    Encapusulating wvanbergen's solution into a function (for your convenience)

    //Convert SQL datetime to unixtime -- by johnboiles
    function datetimeToUnixtime($datetime){
        $result = mysql_query("select unix_timestamp('$datetime')");
        $unixtime = mysql_fetch_array($result);
        return $unixtime[0];
    }
    
    0 讨论(0)
  • 2020-12-10 13:05

    Use strptime() to parse the time and turn it into a structured array.

    Then pass the results of that into the mktime() function to get a UNIX timestamp.

    0 讨论(0)
提交回复
热议问题