如何从例如22-09-2008中获取时间戳?
当前回答
我使用的格式是: $presentDateTime = strtotime(date('Y-m-d H:i:s'));
其他回答
如果你想把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);
使用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/
以下是我的做法:
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'];
这样,您可以让函数知道您使用的日期格式,甚至可以指定时区。
小心使用像strtotime()这样试图“猜测”您的意思的函数(它当然不会猜测,规则在这里)。
事实上,22-09-2008将被解析为2008年9月22日,因为这是唯一合理的事情。
08-09-2008将如何解析?可能是2008年8月9日。
那2008-09-50呢?某些版本的PHP将此解析为20 October 2008。
所以,如果你确定输入的是DD-MM-YYYY格式,最好使用@Armin Ronacher提供的解决方案。
请注意时间/区域,如果你设置它保存在数据库中的日期,因为我得到了一个问题,当我从mysql的日期转换为时间戳使用strtotime比较。在将日期转换为时间戳之前,必须使用完全相同的时间/区域,否则,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)
推荐文章
- 解析日期字符串并更改格式
- 原则-如何打印出真正的sql,而不仅仅是准备好的语句?
- 如何从关联PHP数组中获得第一项?
- PHP/MySQL插入一行然后获取id
- 我如何排序一个多维数组在PHP
- 如何在PHP中截断字符串最接近于一定数量的字符?
- PHP错误:“zip扩展名和unzip命令都没有,跳过。”
- Nginx提供下载。php文件,而不是执行它们
- Java SimpleDateFormat("yyyy-MM-dd' t ' hh:mm:ss' z '")给出的时区为IST
- Json_encode()转义正斜杠
- 在Java中转换字符串到日历对象
- 如何在PHP中捕获cURL错误
- 如何要求一个分叉与作曲家?
- 如何在Android中获取当前日期?
- 如何创建一个日期对象从字符串在javascript