如何在PHP中将日期转换为时间戳?
如何使用以下方法从例如如何在PHP中将日期转换为时间戳?,php,date,timestamp,Php,Date,Timestamp,如何使用以下方法从例如22-09-2008?获取时间戳: 此方法适用于Windows和Unix,并且具有时区意识,这可能是您在使用时想要的 如果您不关心时区,或希望使用服务器使用的时区: $d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00'); if ($d === false) { die("Incorrect date string"); } else { echo $d->getTi
22-09-2008
?获取时间戳:
此方法适用于Windows和Unix,并且具有时区意识,这可能是您在使用时想要的 如果您不关心时区,或希望使用服务器使用的时区:
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093324(这将因服务器时区而异…)
如果要指定时区,请单击此处。(与纽约相同。) 1222093305
或者如果你想用。(与“.”相同) 1222093289
无论如何,在将字符串解析为结构化数据时,严格要求总是一个很好的起点。它可以在将来避免笨拙的调试。因此,我建议始终指定日期格式。还有strtime(),它只需要一种格式:
$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);
<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>
要小心像strtotime()这样的函数,它们试图“猜测”您的意思(当然,它不会猜测) 实际上,
22-09-2008
将被解析为2008年9月22日,因为这是唯一合理的事情
如何解析08-09-2008
?可能是2008年8月9日
那么2008-09-50
呢?一些PHP版本将此解析为2008年10月20日
因此,如果您确定您的输入是
DD-MM-YYYY
格式,最好使用提供的解决方案。如果您知道格式,请使用strtime
,因为strotime
对格式进行猜测,这可能并不总是正确的。由于Windows中未实现strtime
,因此有一个自定义函数
tm_year
是从1900开始的!并且tm_月为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)
以下是我的做法:
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'];
通过这种方式,您可以让函数知道您使用的日期格式,甚至可以指定时区。下面是一个非常简单而有效的解决方案,使用拆分
和mtime
函数:
$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);
它对我来说就像一种魅力。与:
与过程API相同:
$date = date_create('2008-09-22');
echo date_format($date, 'U');
// or
$date = date_create('2008-09-22');
echo date_timestamp_get($date);
如果上述操作因使用而失败,则可以使用
$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');
请注意,如果不设置代码>,则时间部分将设置为当前时间,这与前四个时间不同,前四个时间在省略时间时将使用午夜
另一种选择是使用API:
除非您使用的是本地化的日期字符串,否则更容易的选择可能是DateTime。函数date\u to\u stamp($date,$slash\u time=true,$timezone='Europe/London',$expression=“#^\d{2}([^\d]*)\d{2}([^\d]*)\d{4}$\is”){
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) . '<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
$return=false;
$\u timezone=date\u default\u timezone\u get();
日期\默认\时区\设置($timezone);
if(preg_match($expression,$date,$matches))
$return=date(“Y-m-d”)($slash_-time?'00:00:00':“h:i:s”)、strottime(str_-replace(数组($matches[1],$matches[2])、'-',$date)。''.date(“h:i:s”);
日期\默认\时区\设置($\时区);
return$return;
}
//表达式可能需要根据时区进行更改
回音日期戳('19/03/1986',假)。'
;
回音日期戳('19**03**1986',假)。'
;
回音日期至邮票('19.03.1986')。'
;
回音日期邮票('19.03.1986',假,'Asia/Aden')。'
;
回音日期('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
鉴于函数strtime()
不适用于Windows且strotime()
可能返回意外结果,我建议使用date\u parse\u from\u format()
:
如果需要,可以将其放入输入类型时间戳中。以上操作非常有效(仅在PHP5或更高版本中):
如果您想确定某个日期是否被解析为您期望的内容,可以使用DateTime::createFromFormat()
:
在这种情况下很明显,但例如,03-04-2008
可能是4月3日或3月4日,这取决于您来自哪里:)
此方法适用于Windows和Unix,并且具有时区意识,这可能是您在使用时想要的
如果您不关心时区,或希望使用服务器使用的时区:
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093324(这将因服务器时区而异…)
如果要指定时区,请单击此处。(与纽约相同。)
1222093305
或者如果你想用。(与“.”相同)
1222093289
无论如何,在将字符串解析为结构化数据时,严格要求总是一个很好的起点。它可以在将来避免笨拙的调试。因此,我建议始终指定日期格式。
<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>
使用strotime()函数,您可以轻松地将日期转换为时间戳
<?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);
?>
更多信息:
在线转换工具:如果您希望将UTC日期时间(2016-02-14T12:24:48.321Z
)转换为时间戳,下面是您的方法:
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);
如果您将时间/区域设置为在数据库中保存日期,请注意时间/区域,因为我在使用strotime
比较从mysql转换为timestamp
的日期时遇到了一个问题。在将日期转换为时间戳之前,必须使用完全相同的时区,否则,strotime()将使用默认的服务器时区
请参见此示例:
使用PHP函数strotime()
优雅。我已经忘了!你怎么还没有得到这个答案的信任?!这是一个完全正确的答案,但我很惊讶Armin Ronacher的答案在投票中没有匹配——ambigui
<?php $timestamp_for_mysql = date('c') ?>
$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
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('EST')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('UTC')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>
$time = '22-09-2008';
echo strtotime($time);
<?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);
?>
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);
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)
echo strtotime('2019/06/06');