如何使用jQuery以秒为单位获取两个时间戳之间的时差? [英] How to get time difference between two timestamps in seconds with jQuery?
问题描述
我想基于MySQL时间戳显示 x秒前
。
I want to display x seconds ago
based on a MySQL Timestamp.
我发现该插件名为< a href =http://timeago.yarp.com/ =noreferrer> timeago
但我找不到办法让它成功只显示秒数。
But I cannot find a way to make it display only seconds.
我可以用61秒或300秒。有没有办法使用timeago或纯jQuery / JavaScript将输出转换为秒?
I'm OK with 61 seconds, or 300 seconds. Any way to convert the output to seconds with timeago, or with pure jQuery / JavaScript ?
感谢您的帮助!
示例案例:
$time1 = "2014-02-02 23:54:04"; // plus PHP ways to format it.
//$time2 = NOW() , or date(); whatever.
我只想知道自 $ time1 $ c以来的秒数$ c>。
工作代码:
<script type="text/javascript">
$(function(){
var d2 = new Date();
var d1 = new Date("2014-02-02 23:54:04");
$("a#timedif").html("Diff. Seconds : "+((d2-d1)/100).toString());
// note that you may want to round the value
});
</script>
输出差异。秒:NaN
推荐答案
假设您将字符串解析为JavaScript日期对象,您可以执行
(date2 - date1)/ 1000
assuming you parse the string into JavaScript date object, you can do (date2 - date1)/1000
解析mysql格式的时间戳,只需将字符串输入新的Date():
to parse mysql format timestamp, just feed the string into new Date():
var d2 = new Date('2038-01-19 03:14:07');
var d1 = new Date('2038-01-19 03:10:07');
var seconds = (d2- d1)/1000;
修正问题中的编辑2:
<script type="text/javascript">
$(function(){
var d2 = new Date();
var d1 = new Date("2014-02-02 23:54:04");
$("a#timedif").html("Diff. Seconds : "+((d2-d1)/1000).toString());
});
这篇关于如何使用jQuery以秒为单位获取两个时间戳之间的时差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!