如何从例如22-09-2008中获取时间戳?
当前回答
对于PHP >=5.3, 7和8,这可能工作-
$date = date_parse_from_format('%Y-%m-%d', "2022-11-15"); //here you can give your desired date in desired format.
//just need to keep in mind that date and format matches.
$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year'] + 2000); //this will return the timestamp
$finalDate= date('Y-m-d H:i:s', $timestamp); //now you can convert your timestamp to desired dateTime format.
文档:
date_parse_from_format () mktime () 日期()
其他回答
这个方法在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
无论如何,在将字符串解析为结构化数据时,严格总是一个好的起点。这样可以省去将来调试的麻烦。因此,我建议始终指定日期格式。
下面是一个非常简单而有效的解决方案,使用split和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);
这对我来说就像魔法一样。
我使用的格式是: $presentDateTime = strtotime(date('Y-m-d H:i:s'));
对于PHP >=5.3, 7和8,这可能工作-
$date = date_parse_from_format('%Y-%m-%d', "2022-11-15"); //here you can give your desired date in desired format.
//just need to keep in mind that date and format matches.
$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year'] + 2000); //this will return the timestamp
$finalDate= date('Y-m-d H:i:s', $timestamp); //now you can convert your timestamp to desired dateTime format.
文档:
date_parse_from_format () mktime () 日期()
使用PHP函数strtotime()
echo strtotime('2019/06/06');
date -格式化本地时间/日期
推荐文章
- 如何实现一个好的脏话过滤器?
- PHP中的三个点(…)是什么意思?
- Guzzlehttp -如何从guzzle6得到响应的正文?
- 如何在c#中获得正确的时间戳
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PHP中获得变量名作为字符串?
- 如何减去日期/时间在JavaScript?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 在PHP中对动态变量名使用大括号
- 将Date对象转换为日历对象