日期和当前时间之间的时差? [英] Time difference between a Date and current Time?

查看:167
本文介绍了日期和当前时间之间的时差?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个有趣的视频网站向用户显示有趣的视频。在每个视频下方,我想根据视频的时间戳和当前时间,在5秒前,31分钟前,昨天,2天前内有一个声明。



我的时间戳格式为: 2011-10-17 07:08:00



我的日期不太好,但我猜测我需要找到2个日期/时间之间的差异,以秒为单位,然后决定是否在0秒之间& 60秒以秒显示,或60秒和3600秒显示分钟,或3600秒和3600x24sec,以小时显示,在3600x24sec& 3600x24x2sec显示昨天,等等...我相信我应该使用 strtotime()但我似乎找不到目前的时间,因为我找到的那些解决方案 new date()似乎不起作用



我该怎么做?



Btw,侧面的问题,当我插入一个MySQL时间戳列时,将$ code> 2011-10-17,7:08 PM EDT / / c $ c>转换为 2011-10-17 07:08:00 这是AM。如何将其存储在正确的AM / PM?

解决方案

您可以使用 php的日期时间函数。

  $ datetime1 = new DateTime('2011-10-17 07:08:00'); 
$ datetime2 = new DateTime();
$ interval = $ datetime1-> diff($ datetime2);
echo $ interval-> format('%R%a days');

从这里可以使用一些if语句输出另一种格式的时差(秒,分钟,小时,月份等)取决于实际的时差!输出的格式是找到 here


Assume I have a funny video site that shows funny videos to users. Below every video, I want to have a statement that says "5 seconds ago", "31 minutes ago", "Yesterday", "2 days ago" based on a timestamp of the video and the current time.

The timestamp that I have is in the format: 2011-10-17 07:08:00.

I'm not too good with dates, but I'm guessing that I need to find the difference between the 2 date/time in seconds, then decide if its between 0sec & 60sec to display in seconds, or between 60sec & 3600sec to display in minutes, or between 3600sec & 3600x24sec to display in hours, between 3600x24sec & 3600x24x2sec to display yesterday, and so on... I believe I should be using strtotime() but I cant seem to find the current time as those solutions I found used new date() which does not seem to work!

How can I do this?

Btw, side question, when I insert 2011-10-17, 7:08PM EDT into a MySQL timestamp column, it gets converted to 2011-10-17 07:08:00 which is AM. How can I get it to be stored in the correct AM/PM?

解决方案

You can use the DateTime functions of php.

$datetime1 = new DateTime('2011-10-17 07:08:00');
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

From here on you can use some if-statements to output the time difference in another format (seconds, minutes, hours, month, etc.) depending on the actual time difference! The formats for the output are to find here

这篇关于日期和当前时间之间的时差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆