2017-08-06 23 views
1

如果我CONSOLE.LOG我的日期時間(console.log(dateTime)),結果是這樣的:如何在JavaScript中設置比較日期時間?

06-08-2017 16:05:00 

這是一個字符串。我想比較日期時間和當前日期時間+ 5小時。如果我的日期時間< =當前日期時間+ 5小時,則消息警報:失敗

我該怎麼辦?

回答

3

您可以試試moment.js https://momentjs.com/docs/。這是非常方便的

var date = moment("06-08-2017 16:05:00", "DD-MM-YYYY HH:mm") 
 
var now = moment().add(5, 'h'); 
 

 
//alert(now); 
 

 
if (date < now) { 
 
    alert('Fail'); 
 
} else { 
 
    alert('Success'); 
 
} 
 

 
//or 
 

 
if (date.isBefore(now)) { 
 
    alert('Fail'); 
 
} else { 
 
    alert('Success'); 
 
}
<script src="https://momentjs.com/downloads/moment.js"></script>

4

您可以分析一個字符串到日期如下:

var date = new Date("06-08-2017 16:05:00"); 

然後將其與當前時間如下比較:

var currentDate = new Date(); 
var differenceInMiliseconds = currentDate - date; 
var differenceInHours = differenceInMiliseconds/1000/60/60; 

你可以檢查的differenceInHours值,並給出了基於警報在那。

+0

'2017年6月8日16:05:00' = 8月6日3017號6月8日2017年。如果我'的console.log(日期)',結果:2017年6月8日 –

0

您可以在日期對象中設置當前小時數+5小時。

currentDateTime = new Date(); 
currentDateTime.setHours(currentDateTime.getHours() + 5) 
if(dateTime <= currentDateTime){ //dateTime is your defined date object 
    alert('Failed'); 
}