简体   繁体   English

仅从字符串获取时间时间戳

[英]getting only time timestamp from string

Suppose I have a time string '9:30' which I want to convert to timestamp. 假设我有一个时间字符串“ 9:30”,我想将其转换为时间戳。 What I do right now is extracting it and manually calculate the timestamp. 我现在要做的是提取它并手动计算时间戳。

list($hour, $minute) = explode(':', '9:30');
$timestamp = $hour * 3600 + $minute * 60;

I'm wondering whether there is a smart way using Carbon or DateTime object. 我想知道是否有使用Carbon或DateTime对象的聪明方法。

use strtotime() manual 使用strtotime() 手册

$time = '9:30';
$timestamp = strtotime($time);
echo date('H:i',$timestamp);

I don't think you'll be able to get a timestamp from only hour or minute, as timestamp is number of seconds from 00:00:00 Thursday 1 January 1970 (check wikipedia link for more details). 我认为您不能仅从小时或分钟就获得时间戳,因为时间戳是1970年1月1日(星期四)00:00:00的秒数(有关更多详细信息,请参阅Wikipedia链接 )。 So without the date part you can't have a timestamp. 因此,没有日期部分,您将没有时间戳。 Could you please explain how you're planning to use this? 您能否解释一下您打算如何使用它?

If you're planning to calculate a different timestamp from a given datetime, then you can just do it differently. 如果您打算从给定的日期时间计算出不同的时间戳,则可以采用不同的方法。 Say you're planning to get the timestamp 1 day or 24 hours after given time, then you can do it like this (non object oriented way): 假设您打算在给定时间后的1天或24小时获得时间戳,那么您可以这样做(非面向对象的方式):

$givenTimestamp = strtotime('17-06-2018 09:30:00');
$dayInSeconds = 24*60*60;
$calculatedTimeStamp = $givenTimestamp + $dayInSeconds;

If you're just trying to get how many seconds has been passed for the time section of the timestamp (like 9:30 in your example for a given day), then you can just do it like this: 如果您只是想获取时间戳记的时间部分已经经过了多少秒(例如,给定日期中示例中的9:30),那么您可以这样做:

list($hour, $minute) = explode(':', date ('H:i', strtotime('2018-06-16 09:30:00')));
$secondsSinceStartOfDay = intval($hour)*60*60 + intval($minute) * 60;

You may get the same result without using the intval on $hour and $minute, but it would be better to use intval on them to avoid possible issues in some cases. 在$ hour和$ minute上不使用intval可能会得到相同的结果,但是最好在它们上使用intval以避免在某些情况下可能出现的问题。

Update with Carbon 用碳更新

From Carbon documentation, it seems like you still need the date part to generate the timestamp. 从Carbon文档中看来,您仍然需要日期部分来生成时间戳。 So if you have your $date like this '2018-06-16' and $time like this '09:30', then you can recreate your datetime like this: 因此,如果您的$ date像这样的“ 2018-06-16”,而$ time像这样的“ 09:30”,那么您可以像这样重新创建日期时间:

$dateTimeString = $date .' '. $time .':00';
$carbonDateTime = Carbon::parse($dateTimeString);
// $carbonDateTime will now have your date time reference
// you can now get the timestamp like this
echo $carbonDateTime->timestamp;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM