简体   繁体   English

php mysql 经过时间计算

[英]php mysql time elapsed calculation

I have an app [iphone], that sends to a server some times [using json], so the times look like hh:mm 24 hour format, the time gets saved in the db as varchar,我有一个应用程序 [iphone],它有时会 [使用 json] 发送到服务器,所以时间看起来像 hh:mm 24 小时格式,时间作为 varchar 保存在数据库中,

I need to calculate the elapsed time = endTime - startTime我需要计算经过的时间 = endTime - startTime

but my problem is that I have the time in the db as varchar,, no time stamp,但我的问题是我在数据库中有时间作为varchar,没有时间戳,

  • so how to calculate the elapsed time, with out changing the varchar type of field in my db?, can I convert this hh:mm to an int?那么如何计算经过的时间,而不改变我的数据库中字段的 varchar 类型?,我可以将这个 hh:mm 转换为 int 吗? for the operation?, and then showing it again as a hh:mm, possibly to save in other table?操作?,然后再次显示为 hh:mm,可能保存在其他表中?

thanks a lot!多谢!

so how to calculate the elapsed time, with out changing the varchar type of field in my db?那么如何计算经过的时间,而不改变我的数据库中的 varchar 类型的字段?

You can cast it, but you'd be better off having that as a datetime to start with.你可以投射它,但你最好把它作为一个日期时间开始。

 cast(endtime as datetime) - cast(starttime as datetime) -- yields an interval

In PHP:在 PHP 中:

$json_time = '13:10';
$json_format = 'H:i';

$date = DateTime::createFromFormat($json_format, $json_time);

$mysql_format = 'Y-m-d H:i:s';
echo "Format: $mysql_format; " . $date->format($mysql_format) . "\n";

echo $date->getTimestamp();

Yeilds:产量:

Format: Ymd H:i:s;格式:Ymd H:i:s; 2011-06-08 13:10:00 2011-06-08 13:10:00

1307495400 1307495400

Easy:简单的:

$start_time = '11:10';
$end_time = '18:55';

$start_time = explode(':', $start_time);
$end_time = explode(':', $end_time);

$elapsed_time = $end_time[0]*60+$end_time[1]-$start_time[0]*60-$start_time[1];
// in minutes.
$elapsed_hours = floor($elapsed_time/60);
$elapsed_minutes = $elapsed_time-$elapsed_hours*60;

print $elapsed_hours.':'.$elapsed_minutes;
// 7:45

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

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