首页 文章

如何在PHP中将日期转换为时间戳?

提问于
浏览
306

如何获取时间戳,例如: 22-09-2008

19 回答

  • 113

    PHP的strtotime()给出了

    $timestamp = strtotime('22-09-2008');
    

    哪个适用于Supported Date and Time Formats Docs .

  • 6

    还有strptime(),它只需要一种格式:

    $a = strptime('22-09-2008', '%d-%m-%Y');
    $timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);
    
  • 46

    随着DateTime API

    $dateTime = new DateTime('2008-09-22'); 
    echo $dateTime->format('U'); 
    
    // or 
    
    $date = new DateTime('2008-09-22');
    echo $date->getTimestamp();
    

    与过程API相同:

    $date = date_create('2008-09-22');
    echo date_format($date, 'U');
    
    // or
    
    $date = date_create('2008-09-22');
    echo date_timestamp_get($date);
    

    如果由于您使用unsupported format而导致上述操作失败,则可以使用

    $date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');
    echo $dateTime->format('U'); 
    
    // or
    
    $date = date_parse_from_format('!d-m-Y', '22-09-2008');
    echo date_format($date, 'U');
    

    请注意,如果未设置 ! ,则时间部分将设置为当前时间,这与前四个时间不同,后者将在省略时间时使用午夜 .

    另一种方法是使用IntlDateFormatter API:

    $formatter = new IntlDateFormatter(
        'en_US',
        IntlDateFormatter::FULL,
        IntlDateFormatter::FULL,
        'GMT',
        IntlDateFormatter::GREGORIAN,
        'dd-MM-yyyy'
    );
    echo $formatter->parse('22-09-2008');
    

    除非您使用本地化日期字符串,否则更容易的选择可能是DateTime .

  • 4

    小心 strtotime() 这样的函数试试"guess"你的意思(当然不是猜测,rules are here) .

    确实 22-09-2008 将被解析为2008年9月22日,因为这是唯一合理的事情 .

    如何解析 08-09-2008 ?可能是2008年8月9日 .

    2008-09-50 怎么样?某些版本的PHP将其解析为2008年10月20日 .

    因此,如果您确定您的输入是 DD-MM-YYYY 格式,则最好使用@Armin Ronacher提供的解决方案 .

  • 117

    如果你有PHP 5.3或以上,

    这个方法适用于 both Windows和Unix andtime-zone 知道,这可能是你想要的,如果你认真使用日期 .

    如果您不关心时区,或者想要使用服务器使用的时区:

    $d = DateTime::createFromFormat('d-m-Y', '22-09-2008');
    echo $d->getTimestamp();
    

    1222093324 (这将根据您的服务器时区而有所不同......)

    如果要指定在哪个时区,这里是EST . (与纽约相同 . )

    $d = DateTime::createFromFormat('d-m-Y', '22-09-2008', new DateTimeZone('EST'));
    echo $d->getTimestamp();
    

    1222093305

    或者如果您想使用UTC . (与“GMT”相同 . )

    $d = DateTime::createFromFormat('d-m-Y', '22-09-2008', new DateTimeZone('UTC'));
    echo $d->getTimestamp();
    

    1222093289

  • 5

    使用mktime

    list($day, $month, $year) = explode('-', '22-09-2008');
    echo mktime(0, 0, 0, $month, $day, $year);
    
  • 5

    使用strtotime()函数可以轻松地将日期转换为时间戳

    <?php
    // set default timezone
    date_default_timezone_set('America/Los_Angeles');
    
    //define date and time
    $date = date("d M Y H:i:s");
    
    // output
    echo strtotime($date);
    ?>
    

    更多信息:http://php.net/manual/en/function.strtotime.php

    在线转换工具:http://freeonlinetools24.com/

  • 7

    这是一个使用 splitmtime 函数的非常简单有效的解决方案:

    $date="30/07/2010 13:24"; //Date example
    list($day, $month, $year, $hour, $minute) = split('[/ :]', $date); 
    
    //The variables should be arranged according to your date format and so the separators
    $timestamp = mktime($hour, $minute, 0, $month, $day, $year);
    echo date("r", $timestamp);
    

    它对我来说就像一个魅力 .

  • 4

    鉴于函数 strptime() 不适用于Windows且 strtotime() 可以返回意外结果,我建议使用 date_parse_from_format()

    $date = date_parse_from_format('d-m-Y', '22-09-2008');
    $timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);
    
  • 179

    如果您想确定日期是否被解析为您期望的内容,您可以使用 DateTime::createFromFormat()

    $d = DateTime::createFromFormat('d-m-Y', '22-09-2008');
    if ($d === false) {
        die("Woah, that date doesn't look right!");
    }
    echo $d->format('Y-m-d'), PHP_EOL;
    // prints 2008-09-22
    

    在这种情况下很明显,但是 03-04-2008 可能是4月3日或3月4日,取决于你来自哪里:)

  • 43

    如果您知道格式使用 strptime ,因为 strtotime 会对格式进行猜测,这可能并不总是正确的 . 由于 strptime 未在Windows中实现,因此存在自定义功能

    请记住,返回值 tm_year 是从1900年开始的!和 tm_month 是0-11

    例:

    $a = strptime('22-09-2008', '%d-%m-%Y');
    $timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900)
    
  • -2
    <?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>
    

    http://php.net/manual/en/function.date.php

  • 5
    $time = '22-09-2008';
    echo strtotime($time);
    
  • 558
    function date_to_stamp( $date, $slash_time = true, $timezone = 'Europe/London', $expression = "#^\d{2}([^\d]*)\d{2}([^\d]*)\d{4}$#is" ) {
        $return = false;
        $_timezone = date_default_timezone_get();
        date_default_timezone_set( $timezone );
        if( preg_match( $expression, $date, $matches ) )
            $return = date( "Y-m-d " . ( $slash_time ? '00:00:00' : "h:i:s" ), strtotime( str_replace( array($matches[1], $matches[2]), '-', $date ) . ' ' . date("h:i:s") ) );
        date_default_timezone_set( $_timezone );
        return $return;
    }
    
    // expression may need changing in relation to timezone
    echo date_to_stamp('19/03/1986', false) . '
    '; echo date_to_stamp('19**03**1986', false) . '
    '; echo date_to_stamp('19.03.1986') . '
    '; echo date_to_stamp('19.03.1986', false, 'Asia/Aden') . '
    '; echo date('Y-m-d h:i:s') . '
    '; //1986-03-19 02:37:30 //1986-03-19 02:37:30 //1986-03-19 00:00:00 //1986-03-19 05:37:30 //2012-02-12 02:37:30
  • 1
    <?php echo date('U') ?>
    

    如果需要,请将其放在MySQL输入类型时间戳中 . 以上工作非常好(仅限PHP 5或更高版本):

    <?php $timestamp_for_mysql = date('c') ?>
    
  • 14

    我是这样做的:

    function dateToTimestamp($date, $format, $timezone='Europe/Belgrade')
    {
        //returns an array containing day start and day end timestamps
        $old_timezone=date_timezone_get();
        date_default_timezone_set($timezone);
        $date=strptime($date,$format);
        $day_start=mktime(0,0,0,++$date['tm_mon'],++$date['tm_mday'],($date['tm_year']+1900));
        $day_end=$day_start+(60*60*24);
        date_default_timezone_set($old_timezone);
        return array('day_start'=>$day_start, 'day_end'=>$day_end);
    }
    
    $timestamps=dateToTimestamp('15.02.1991.', '%d.%m.%Y.', 'Europe/London');
    $day_start=$timestamps['day_start'];
    

    这样,您可以让函数知道您正在使用的日期格式,甚至可以指定时区 .

  • 13

    如果你把它设置为在数据库中保存日期,请注意时间/区域,因为当我使用 strtotime 比较转换为 timestamp 的mysql的日期时出现问题 . 在将日期转换为时间戳之前必须使用完全相同的时间/区域,否则strtotime()将使用默认服务器时区 .

    请看这个例子:https://3v4l.org/BRlmV

    function getthistime($type, $modify = null) {
        $now = new DateTime(null, new DateTimeZone('Asia/Baghdad'));
        if($modify) {
            $now->modify($modify);
        }
        if(!isset($type) || $type == 'datetime') {
            return $now->format('Y-m-d H:i:s');
        }
        if($type == 'time') {
            return $now->format('H:i:s');
        }
        if($type == 'timestamp') {
            return $now->getTimestamp();
        }
    }
    function timestampfromdate($date) {
        return DateTime::createFromFormat('Y-m-d H:i:s', $date, new DateTimeZone('Asia/Baghdad'))->getTimestamp();
    }
    
    echo getthistime('timestamp')."--".
        timestampfromdate(getthistime('datetime'))."--".
        strtotime(getthistime('datetime'));
    
    //getthistime('timestamp') == timestampfromdate(getthistime('datetime')) (true)
    //getthistime('timestamp') == strtotime(getthistime('datetime')) (false)
    
  • 4

    使用PHP函数date()

    echo date('m/d/Y', 1299446702);
    

    date — Format a local time/date

  • 0

    如果您要将UTC日期时间( 2016-02-14T12:24:48.321Z )转换为时间戳,请执行以下操作:'s how you' d:

    function UTCToTimestamp($utc_datetime_str)
    {
        preg_match_all('/(.+?)T(.+?)\.(.*?)Z/i', $utc_datetime_str, $matches_arr);
        $datetime_str = $matches_arr[1][0]." ".$matches_arr[2][0];
    
        return strtotime($datetime_str);
    }
    
    $my_utc_datetime_str = '2016-02-14T12:24:48.321Z';
    $my_timestamp_str = UTCToTimestamp($my_utc_datetime_str);
    

相关问题