如何从例如22-09-2008中获取时间戳?
当前回答
$time = '22-09-2008';
echo strtotime($time);
其他回答
<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>
http://php.net/manual/en/function.date.php
请注意时间/区域,如果你设置它保存在数据库中的日期,因为我得到了一个问题,当我从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)
使用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/
如果已经有了该格式的日期,则只需要在PHP中调用“strtotime”函数。
$date = '22-09-2008';
$timestamp = strtotime($date);
echo $timestamp; // 1222041600
或在单行中:
echo strtotime('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();
}
1222093324(这将取决于您的服务器时区…)
如果要指定在哪个时区,请在这里指定EST(与纽约相同)。
$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();
}
1222093305
或者如果你想使用UTC。(与“GMT”相同。)
$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();
}
1222093289
无论如何,在将字符串解析为结构化数据时,严格总是一个好的起点。这样可以省去将来调试的麻烦。因此,我建议始终指定日期格式。
推荐文章
- 从IP地址获取位置
- 如何在python中验证日期字符串格式?
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK
- PHP -获取bool值,当为false时返回false
- 在foreach中通过引用传递
- 如何触发命令行PHP脚本的XDebug分析器?
- 如何找出如果你使用HTTPS没有$_SERVER['HTTPS']
- 更好的方法检查变量为null或空字符串?
- 当使用Composer的开发/生产开关时,如何正确部署?
- 自动删除Laravel (Eloquent ORM)中的相关行
- 如何减去X天从一个日期对象在Java?
- 在取消设置元素后重新设置数组键
- 如何修剪空白的数组值在php
- PHP中的双not(!!)操作符