我正在尝试使用javascript计算时间之间的小时差异。但我一直在控制台中获得结果NaN。我使用javascript获取当前时间和来自localstorage
的延迟时间var log_time = localStorage.getItem('login_time')
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
console.log(log_time);
var today = day + "/" + month + "/" + year
var time = hour + ":" + minute + ":" + second
console.log(today+' '+time);
var date1 = (log_time);
var date2 = (today+' '+time);
var hours = Math.abs(date2 - date1) / 36e5;
console.log(hours.toFixed(2))
localstorage
读取15/7/2017 9:30:46
答案 0 :(得分:0)
localStorage将存储任何对象的字符串化版本,需要解析它。如果您将其转换为毫秒,那么您还需要将其解析为数字,它只能保存字符串
var earlierDate = new Date( localStorage.getItem('login_time'))
// or var earlierDate = parseInt(localStorage.getItem('login_time'))
var currentDate = new Date()
var diff = currentDate - earlierDate;
然后用您的逻辑
将差异转换为小时/分钟/秒答案 1 :(得分:0)
我不敢回答你在这里想做什么:
date2 - date1
这些是展位字符串,你不能减去它们。但是,您可以将它们转换为自1970年以来的毫秒,然后您可以进行数学运算:
var log_time = localStorage.getItem('login_time').split(" ");
log_time[0]=log_time[0].split("/").reverse().map((el,i)=>i?("0"+el).slice(-2):el).join("-");//5/4/2017 => 2017-04-05
log_time[1]=("0"+log_time[1]).slice(-8);// 9:30:10 => 09:30:10
var difference= new Date() - new Date(log_time.join("T"));
var hours=Math.floor(difference/(1000*60*60 /* one hour in ms */));
您可能会过度隐藏存储的格式。正确解析它非常复杂。
答案 2 :(得分:0)
您需要稍微更改一下日期格式This may Help you 并解析这些日期,因为这些日期格式正在搅拌。
var log_time1 = '2017-07-15 09:30:46';//Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.
var log_time = new Date(log_time1)//string parsing date
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
var today = year + "-" + month + "-" + day
var time = hour + ":" + minute + ":" + second
var date1 = (log_time);
var test_date2 = (today+' '+time);
var date2= new Date(test_date2);//string parsing date
var hours = Math.abs(date2 - date1) / 36e5;
alert(hours.toFixed(2))