繁体   English   中英

PHP字符串到时间戳,不带前导零

[英]PHP String to timestamp without leading zero

我正在尝试将持续时间原始文本转换为实际时间戳,但格式没有任何前导零,并且没有 DateTime 将无法工作,我真的不知道如何从字符串中拆分值,我也是可能有几个小时取决于字符串本身,所以它可能是 1:59 或 1:30:49,这是我的实际尝试

$time = "1:59";    
$duration_not_raw = DateTime::createFromFormat('H:i:s', $time);

$time2 = "1:51:59";
$duration_not_raw2 = DateTime::createFromFormat('H:i:s', $time2); 

但显然它打破了我的整个页面,如果我能够拆分我想要的值

if (value) < 10 
{
    "0"..value
}

使用适当的格式字符串("G:i" 代表 $time,"G:i:s" 代表 $time2)而不是 "H:i:s" 代表 DateTime::createFromFormat() 或使用 date_create() 并让php 搞清楚:

$time = "1:59";    
$duration_not_raw = date_create($time);


$time2 = "1:51:59";
$duration_not_raw2 = date_create($time2);

请参阅https://www.php.net/manual/en/datetime.formats.time.php了解 date_create() 可以理解的格式,以及https://www.php.net/manual/en/datetime.createfromformat.php了解与 DateTime::createFromFormat() 一起使用的格式字符串

我用不同的方法解决了它,我很抱歉,因为我第一次不清楚我需要什么。

$str_time = "1:59";
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
$time_milliseconds = $time_seconds * 1000

您不想从日期计算时间戳,而是想将时间间隔(如 1 小时 59 分钟)转换为毫秒。

为了能够为此使用日期函数,必须考虑时间 1970-01-01 和时区 UTC。 使用 DateTime 的解决方案:

$str_time = "1:59";  //1 hour 59 Minutes
$time_milliseconds = date_create('1970-01-01 '.$str_time.' UTC')->getTimeStamp() * 1000;
//7140000

或者使用 strtotime:

$time_milliseconds = strtotime('1970-01-01 '.$str_time.' UTC') * 1000;

用 sscanf 解决这个问题的想法并不是那么糟糕。 但是,不需要区分大小写。 如果秒数丢失,sscanf 返回 NULL。 NULL 在算术运算中被转换为 0。

$str_time = "1:59";
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = $hours * 3600 + $minutes * 60 + $seconds;
$time_milliseconds = $time_seconds * 1000;

但最后但并非最不重要的一点是,有些类可以将时间间隔转换为具有给定单位的值。

$ms = Dt::totalRelTime("1:59",'milliseconds');  //float(7140000)

有关 Dt 类的更多信息

暂无
暂无

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

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