我想根据MySQL时间戳显示x seconds ago
。
我找到了名为timeago
的插件但是我找不到让它只显示秒的方法。
我可以用61秒或300秒。有没有办法使用timeago或纯jQuery / JavaScript将输出转换为秒?
感谢您的帮助!
示例案例
$time1 = "2014-02-02 23:54:04"; // plus PHP ways to format it.
//$time2 = NOW() , or date(); whatever.
我只想知道自$time1
以来的秒数。
工作代码:
<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>
输出Diff. Seconds : NaN
答案 0 :(得分:13)
假设您将字符串解析为JavaScript日期对象,您可以这样做 (date2 - date1)/ 1000
解析mysql格式的时间戳,只需将字符串输入新的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());
});
答案 1 :(得分:1)
如果您对该插件没问题,可以稍微修改它以仅使用秒数
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
seconds < 90 && substitute($l.minute, 1) ||
minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
minutes < 90 && substitute($l.hour, 1) ||
hours < 24 && substitute($l.hours, Math.round(hours)) ||
hours < 42 && substitute($l.day, 1) ||
days < 30 && substitute($l.days, Math.round(days)) ||
days < 45 && substitute($l.month, 1) ||
days < 365 && substitute($l.months, Math.round(days / 30)) ||
years < 1.5 && substitute($l.year, 1) ||
substitute($l.years, Math.round(years));
使用此部分,只需转换为秒
答案 2 :(得分:0)
jQuery只是一个JavaScript库,因此JavaScript将在您的jQuery脚本中运行:
// specified date:
var oneDate = new Date("November 02, 2017 06:00:00");
// number of milliseconds since midnight Jan 1 1970 till specified date
var oneDateMiliseconds = oneDate.getTime();
// number of milliseconds since midnight Jan 1 1970 till now
var currentMiliseconds = Date.now();
// return time difference in milliseconds
var timePassedInMilliseconds = (currentMiliseconds-oneDateMiliseconds)/1000;
alert(timePassedInMilliseconds);
答案 3 :(得分:0)
我使用时差来分别计算每个值
var start = new Date('Mon Jul 30 2018 19:35:35 GMT+0500');
var end = new Date('Mon Jul 30 2018 21:15:00 GMT+0500');
var hrs = end.getHours() - start.getHours();
var min = end.getMinutes() - start.getMinutes();
var sec = end.getSeconds() - start.getSeconds();
var hour_carry = 0;
var minutes_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hrs = hrs - hour_carry;
if(sec < 0){
sec += 60;
minutes_carry += 1;
}
min = min - minutes_carry;
console.log("hrs",hrs);
console.log("min",min);
console.log("sec",sec);
console.log(hrs + "hrs " + min +"min " + sec + "sec");
答案 4 :(得分:0)
获得两个时间戳之间的差异
秒: (通过新的Date()。getTime()获得时间戳)
diff_in_time = (timestamp_1 - timestamp2);
以天计:
diff_in_days = parseInt((timestamp_1 - timestamp2) / (1000 * 3600 * 24));