How do I get timestamp from e.g. 22-09-2008
?
我如何从22-09-2008获得时间戳?
19 个解决方案
#1
540
PHP's strtotime()
gives
PHP的strtotime()
$timestamp = strtotime('22-09-2008');
Which does work with the Supported Date and Time Formats Docs.
它使用支持的日期和时间格式文档。
#2
177
There is also strptime()
which expects exactly one format:
还有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);
#3
112
With DateTime
API:
DateTime API:
$dateTime = new DateTime('2008-09-22'); echo $dateTime->format('U'); // or $date = new DateTime('2008-09-22');echo $date->getTimestamp();
The same with the procedural API:
程序API也是如此:
$date = date_create('2008-09-22');echo date_format($date, 'U');// or$date = date_create('2008-09-22');echo date_timestamp_get($date);
If the above fails because you are using a unsupported format, you can use
如果由于使用不受支持的格式而导致上述失败,则可以使用
$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');
Note that if you do not set the !
, the time portion will be set to current time, which is different from the first four which will use midnight when you omit the time.
注意,如果不设置!,时间部分将被设置为当前时间,这与前4个不同,当您省略时间时将使用午夜。
Yet another alternative is to use the IntlDateFormatter
API:
另一种选择是使用IntlDateFormatter API:
$formatter = new IntlDateFormatter( 'en_US', IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'GMT', IntlDateFormatter::GREGORIAN, 'dd-MM-yyyy');echo $formatter->parse('22-09-2008');
Unless you are working with localized date strings, the easier choice is likely DateTime.
除非使用本地化的日期字符串,否则更容易的选择可能是DateTime。
#4
112
Be careful with functions like strtotime()
that try to "guess" what you mean (it doesn't guess of course, the rules are here).
要小心像strtotime()这样的函数,它们试图“猜测”您的意思(当然,它并不猜测,规则在这里)。
Indeed 22-09-2008
will be parsed as 22 September 2008, as it is the only reasonable thing.
实际上,22-09-2008将被分析为2008年9月22日,因为这是唯一合理的事情。
How will 08-09-2008
be parsed? Probably 09 August 2008.
如何分析08-09-2008 ?2008年8月可能09年。
What about 2008-09-50
? Some versions of PHP parse this as 20 October 2008.
2008-09-50怎么样?PHP的一些版本将此解析为2008年10月20日。
So, if you are sure your input is in DD-MM-YYYY
format, it's better to use the solution offered by @Armin Ronacher.
所以,如果您确定输入是DD-MM-YYYY格式,最好使用@Armin Ronacher提供的解决方案。
#5
42
If you have PHP 5.3 or above,
如果你有PHP 5.3或以上版本,
this method works on both Windows and Unix and is time-zone aware, which is probably what you want if you are serious about working with dates.
这个方法在Windows和Unix上都有效,并且是时区感知的,如果你认真对待日期,这可能就是你想要的。
If you don't care about timezone, or want to use the time zone your server uses:
如果您不关心时区,或者希望使用服务器使用的时区:
$d = DateTime::createFromFormat('d-m-Y', '22-09-2008');echo $d->getTimestamp();
1222093324 (This will differ depending on your server time zone...)
1222093324(这取决于你的服务器时区…)
If you want to specify in which time zone, here EST. (Same as New York.)
如果你想指定哪个时区,这里是。(和纽约一样。)
$d = DateTime::createFromFormat('d-m-Y', '22-09-2008', new DateTimeZone('EST'));echo $d->getTimestamp();
1222093305
1222093305
Or if you want to use UTC. (Same as "GMT".)
或者如果你想使用UTC。(同“格林尼治时间”。)
$d = DateTime::createFromFormat('d-m-Y', '22-09-2008', new DateTimeZone('UTC'));echo $d->getTimestamp();
1222093289
1222093289
#6
41
Using mktime:
使用mktime:
list($day, $month, $year) = explode('-', '22-09-2008');echo mktime(0, 0, 0, $month, $day, $year);
#7
14
Using strtotime() function you can easily convert date to timestamp
使用strtotime()函数可以轻松地将日期转换为时间戳
<?php// set default timezonedate_default_timezone_set('America/Los_Angeles');//define date and time$date = date("d M Y H:i:s");// outputecho strtotime($date);?>
More info: http://php.net/manual/en/function.strtotime.php
更多信息:http://php.net/manual/en/function.strtotime.php。
Online conversion tool: http://freeonlinetools24.com/
在线转换工具:http://freeonlinetools24.com/
#8
13
Here is a very simple and effective solution using the split
and mtime
functions:
使用split和mtime函数,有一个非常简单有效的解决方案:
$date="30/07/2010 13:24"; //Date examplelist($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);
It worked like a charm for me.
它对我来说就像一种魅力。
#9
7
Given that the function strptime()
does not work for Windows and strtotime()
can return unexpected results, I recommend using date_parse_from_format()
:
如果函数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']);
#10
6
If you want to know for sure whether a date gets parsed into something you expect, you can use DateTime::createFromFormat()
:
如果您想确定日期是否被解析为您期望的内容,可以使用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
It's obvious in this case, but e.g. 03-04-2008
could be 3rd of April or 4th of March depending on where you come from :)
这个例子很明显,但是03-04-2008可能是4月3日或3月4日,这取决于你来自哪里:)
#11
5
If you know the format use strptime
because strtotime
does a guess for the format, which might not always be correct. Since strptime
is not implemented in Windows there is a custom function
如果您知道格式,则使用strptime,因为strtotime会猜测格式,这可能并不总是正确的。由于strptime没有在Windows中实现,所以有一个自定义函数
- http://nl3.php.net/manual/en/function.strptime.php#86572
- http://nl3.php.net/manual/en/function.strptime.php # 86572
Remember that the returnvalue tm_year
is from 1900! and tm_month
is 0-11
记住,返回值tm_year是从1900年开始的!和tm_month划分的
Example:
例子:
$a = strptime('22-09-2008', '%d-%m-%Y');$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900)
#12
5
<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>
http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.date.php
#13
5
$time = '22-09-2008';echo strtotime($time);
#14
4
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 timezoneecho date_to_stamp('19/03/1986', false) . '<br />';echo date_to_stamp('19**03**1986', false) . '<br />';echo date_to_stamp('19.03.1986') . '<br />';echo date_to_stamp('19.03.1986', false, 'Asia/Aden') . '<br />';echo date('Y-m-d h:i:s') . '<br />';//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
#15
4
<?php echo date('U') ?>
If you want, put it in a MySQL input type timestamp. The above works very well (only in PHP 5 or later):
如果需要,请将其放入MySQL输入类型的时间戳中。以上方法非常有效(仅适用于PHP 5或更高版本):
<?php $timestamp_for_mysql = date('c') ?>
#16
4
Here is how I'd do it:
下面是我的做法:
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'];
This way, you let the function know what date format you are using and even specify the timezone.
通过这种方式,您可以让函数知道您正在使用的日期格式,甚至指定时区。
#17
1
Please be careful about time/zone if you set it to save dates in database, as I got an issue when I compared dates from mysql that converted to timestamp
using strtotime
. you must use exactly same time/zone before converting date to timestamp otherwise, strtotime() will use default server timezone.
如果您将它设置为在数据库中保存日期,请注意时间/区域,因为当我比较使用strtotime将mysql中的日期转换为时间戳时,我遇到了一个问题。在将日期转换为时间戳之前,必须使用完全相同的时区,否则strtotime()将使用默认的服务器时区。
Please see this example: https://3v4l.org/BRlmV
请参见这个示例: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)
#18
0
Use PHP function date()
使用PHP函数日期()
echo date('m/d/Y', 1299446702);
date — Format a local time/date
日期-格式化当地时间/日期
#19
-2
If you're looking to convert a UTC datetime (2016-02-14T12:24:48.321Z
) to timestamp, here's how you'd do it:
如果您希望将UTC datetime (2016-02-14T12:24:48.321Z)转换为timestamp,您可以这样做:
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);
#1
540
PHP's strtotime()
gives
PHP的strtotime()
$timestamp = strtotime('22-09-2008');
Which does work with the Supported Date and Time Formats Docs.
它使用支持的日期和时间格式文档。
#2
177
There is also strptime()
which expects exactly one format:
还有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);
#3
112
With DateTime
API:
DateTime API:
$dateTime = new DateTime('2008-09-22'); echo $dateTime->format('U'); // or $date = new DateTime('2008-09-22');echo $date->getTimestamp();
The same with the procedural API:
程序API也是如此:
$date = date_create('2008-09-22');echo date_format($date, 'U');// or$date = date_create('2008-09-22');echo date_timestamp_get($date);
If the above fails because you are using a unsupported format, you can use
如果由于使用不受支持的格式而导致上述失败,则可以使用
$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');
Note that if you do not set the !
, the time portion will be set to current time, which is different from the first four which will use midnight when you omit the time.
注意,如果不设置!,时间部分将被设置为当前时间,这与前4个不同,当您省略时间时将使用午夜。
Yet another alternative is to use the IntlDateFormatter
API:
另一种选择是使用IntlDateFormatter API:
$formatter = new IntlDateFormatter( 'en_US', IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'GMT', IntlDateFormatter::GREGORIAN, 'dd-MM-yyyy');echo $formatter->parse('22-09-2008');
Unless you are working with localized date strings, the easier choice is likely DateTime.
除非使用本地化的日期字符串,否则更容易的选择可能是DateTime。
#4
112
Be careful with functions like strtotime()
that try to "guess" what you mean (it doesn't guess of course, the rules are here).
要小心像strtotime()这样的函数,它们试图“猜测”您的意思(当然,它并不猜测,规则在这里)。
Indeed 22-09-2008
will be parsed as 22 September 2008, as it is the only reasonable thing.
实际上,22-09-2008将被分析为2008年9月22日,因为这是唯一合理的事情。
How will 08-09-2008
be parsed? Probably 09 August 2008.
如何分析08-09-2008 ?2008年8月可能09年。
What about 2008-09-50
? Some versions of PHP parse this as 20 October 2008.
2008-09-50怎么样?PHP的一些版本将此解析为2008年10月20日。
So, if you are sure your input is in DD-MM-YYYY
format, it's better to use the solution offered by @Armin Ronacher.
所以,如果您确定输入是DD-MM-YYYY格式,最好使用@Armin Ronacher提供的解决方案。
#5
42
If you have PHP 5.3 or above,
如果你有PHP 5.3或以上版本,
this method works on both Windows and Unix and is time-zone aware, which is probably what you want if you are serious about working with dates.
这个方法在Windows和Unix上都有效,并且是时区感知的,如果你认真对待日期,这可能就是你想要的。
If you don't care about timezone, or want to use the time zone your server uses:
如果您不关心时区,或者希望使用服务器使用的时区:
$d = DateTime::createFromFormat('d-m-Y', '22-09-2008');echo $d->getTimestamp();
1222093324 (This will differ depending on your server time zone...)
1222093324(这取决于你的服务器时区…)
If you want to specify in which time zone, here EST. (Same as New York.)
如果你想指定哪个时区,这里是。(和纽约一样。)
$d = DateTime::createFromFormat('d-m-Y', '22-09-2008', new DateTimeZone('EST'));echo $d->getTimestamp();
1222093305
1222093305
Or if you want to use UTC. (Same as "GMT".)
或者如果你想使用UTC。(同“格林尼治时间”。)
$d = DateTime::createFromFormat('d-m-Y', '22-09-2008', new DateTimeZone('UTC'));echo $d->getTimestamp();
1222093289
1222093289
#6
41
Using mktime:
使用mktime:
list($day, $month, $year) = explode('-', '22-09-2008');echo mktime(0, 0, 0, $month, $day, $year);
#7
14
Using strtotime() function you can easily convert date to timestamp
使用strtotime()函数可以轻松地将日期转换为时间戳
<?php// set default timezonedate_default_timezone_set('America/Los_Angeles');//define date and time$date = date("d M Y H:i:s");// outputecho strtotime($date);?>
More info: http://php.net/manual/en/function.strtotime.php
更多信息:http://php.net/manual/en/function.strtotime.php。
Online conversion tool: http://freeonlinetools24.com/
在线转换工具:http://freeonlinetools24.com/
#8
13
Here is a very simple and effective solution using the split
and mtime
functions:
使用split和mtime函数,有一个非常简单有效的解决方案:
$date="30/07/2010 13:24"; //Date examplelist($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);
It worked like a charm for me.
它对我来说就像一种魅力。
#9
7
Given that the function strptime()
does not work for Windows and strtotime()
can return unexpected results, I recommend using date_parse_from_format()
:
如果函数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']);
#10
6
If you want to know for sure whether a date gets parsed into something you expect, you can use DateTime::createFromFormat()
:
如果您想确定日期是否被解析为您期望的内容,可以使用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
It's obvious in this case, but e.g. 03-04-2008
could be 3rd of April or 4th of March depending on where you come from :)
这个例子很明显,但是03-04-2008可能是4月3日或3月4日,这取决于你来自哪里:)
#11
5
If you know the format use strptime
because strtotime
does a guess for the format, which might not always be correct. Since strptime
is not implemented in Windows there is a custom function
如果您知道格式,则使用strptime,因为strtotime会猜测格式,这可能并不总是正确的。由于strptime没有在Windows中实现,所以有一个自定义函数
- http://nl3.php.net/manual/en/function.strptime.php#86572
- http://nl3.php.net/manual/en/function.strptime.php # 86572
Remember that the returnvalue tm_year
is from 1900! and tm_month
is 0-11
记住,返回值tm_year是从1900年开始的!和tm_month划分的
Example:
例子:
$a = strptime('22-09-2008', '%d-%m-%Y');$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900)
#12
5
<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>
http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.date.php
#13
5
$time = '22-09-2008';echo strtotime($time);
#14
4
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 timezoneecho date_to_stamp('19/03/1986', false) . '<br />';echo date_to_stamp('19**03**1986', false) . '<br />';echo date_to_stamp('19.03.1986') . '<br />';echo date_to_stamp('19.03.1986', false, 'Asia/Aden') . '<br />';echo date('Y-m-d h:i:s') . '<br />';//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
#15
4
<?php echo date('U') ?>
If you want, put it in a MySQL input type timestamp. The above works very well (only in PHP 5 or later):
如果需要,请将其放入MySQL输入类型的时间戳中。以上方法非常有效(仅适用于PHP 5或更高版本):
<?php $timestamp_for_mysql = date('c') ?>
#16
4
Here is how I'd do it:
下面是我的做法:
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'];
This way, you let the function know what date format you are using and even specify the timezone.
通过这种方式,您可以让函数知道您正在使用的日期格式,甚至指定时区。
#17
1
Please be careful about time/zone if you set it to save dates in database, as I got an issue when I compared dates from mysql that converted to timestamp
using strtotime
. you must use exactly same time/zone before converting date to timestamp otherwise, strtotime() will use default server timezone.
如果您将它设置为在数据库中保存日期,请注意时间/区域,因为当我比较使用strtotime将mysql中的日期转换为时间戳时,我遇到了一个问题。在将日期转换为时间戳之前,必须使用完全相同的时区,否则strtotime()将使用默认的服务器时区。
Please see this example: https://3v4l.org/BRlmV
请参见这个示例: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)
#18
0
Use PHP function date()
使用PHP函数日期()
echo date('m/d/Y', 1299446702);
date — Format a local time/date
日期-格式化当地时间/日期
#19
-2
If you're looking to convert a UTC datetime (2016-02-14T12:24:48.321Z
) to timestamp, here's how you'd do it:
如果您希望将UTC datetime (2016-02-14T12:24:48.321Z)转换为timestamp,您可以这样做:
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);