在 PHP 中将时间转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36144660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:43:27  来源:igfitidea点击:

Convert time to integer in Php

php

提问by Danielle Rose Mabunga

How would you convert time to integer?

你如何将时间转换为整数?

 string(8) "04:04:07"

I want this as 4(hours) or much better 4.04(4hours and 4 minutes)

我希望这是 4(小时)或更好的 4.04(4 小时和 4 分钟)

I tried

我试过

  $yourdatetime = "04:04:07";
  $timestamp = strtotime($yourdatetime);

Which results in

这导致

 int(1458590887)

回答by random_user_name

The datefunction is your friend:

日期的功能是你的朋友:

Given your own code above:

鉴于上面你自己的代码:

$yourdatetime = "04:04:07";
$timestamp = strtotime($yourdatetime);

You can then feed it into the date function:

然后,您可以将其输入到日期函数中:

echo 'Hours:' . date('h', $timestamp);  // Hours: 04
echo 'Minutes:' . date('i', $timestamp); // Minutes: 04
echo 'Seconds:' . date('s', $timestamp); // Seconds: 07

Refer to the docsfor the specific format(s) you'd like for hours - there's many options.

请参阅文档以了解您想要几个小时的特定格式 - 有很多选择。

You could even do it in one move:

你甚至可以一步完成:

echo date('h.i', $timestamp); // 04.04

If you need it truly numeric:

如果你需要它真正的数字:

echo float(date('h.i', $timestamp)); // 4.04

回答by James Paterson

strtotime()returns the time in seconds since the Unix Epoch. You can then format this using date(). Documentation for date: http://php.net/manual/en/function.date.php

strtotime()返回自 Unix 纪元以来的时间(以秒为单位)。然后,您可以使用date(). 日期文档:http: //php.net/manual/en/function.date.php

To get the number of hours (4):

获取小时数 (4):

$timestamp = date("g",strtotime($yourdatetime));

To get the number of hours and minutes (4.03):

获取小时数和分钟数 (4.03):

$timestamp = date("g.i",strtotime($yourdatetime));

回答by fusion3k

Use (float)and preg_replaceto one-line-code conversion:

使用(float)preg_replace到一行代码转换:

$floatval = (float) preg_replace('/^(\d+):(\d+).+/','.',$yourdatetime);

回答by Machavity

So we'll break this out. If we cast the hours as an integer and leave the minutes as a string this is a pretty simple conversion

所以我们会打破这个。如果我们将小时数转换为整数并将分钟数保留为字符串,这是一个非常简单的转换

$time = explode(':', $yourdatetime);
$hours = (int)$time[0] . '.' . $time[1];

Avoids any overhead from regex

避免正则表达式的任何开销