2017-07-15 158 views
0

我試圖計算使用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

'date2'是一個字符串,'date1'是一個字符串,當你減去兩個字符串時,你會發生什麼? –

回答

0

您需要更改日期格式點點This may Help you並解析這些,因爲這些都是stirng甲日期。

Working Fiddle

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)) 
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; 

然後轉換diff來時/分/秒,你的邏輯

0

我不是舒爾什麼youre試圖在這裏做:

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 */)); 

您可以overthink的存儲格式。解析它很複雜。

http://jsbin.com/fofowayata/edit?console

+0

它仍然讀取NaN – user6579134

+0

@ user6579134是。編輯 –