[英]Moment js date time compare
我正在從javascript函數進行API調用,該函數正確返回了JSON響應。 但是,當我逐步執行JSON響應時,當我使用moment().isSameOrBefore
行時,我收到了棄用警告以及Function.createFromInputFallback(moment.js line:320) moment().isSameOrBefore
。 我對javascript還是相當陌生的,尤其是Node的即時包。
基本上,我想確定在執行此功能時哪個預測潮汐最接近當前時間。 這是使用moment().isSameOrBefore
參數的正確方法,並且/或者我是否應該修改代碼以進行不同的處理?
這是JSON:
{ "predictions" : [ {"t":"2018-06-08 03:06", "v":"3.795", "type":"H"},{"t":"2018-06-08 09:25", "v":"0.443", "type":"L"},{"t":"2018-06-08 15:51", "v":"3.884", "type":"H"},{"t":"2018-06-08 22:01", "v":"0.778", "type":"L"} ]}
這是我的功能:
const getTide = require('./modules/getTide.js');
var moment = require('moment');
async function testMod() {
await getTide.getQuote().then(function(value){
const parsedData = JSON.parse(value);
let text = " ";
// This loop steps through the JSON response row by row to test the data
var i;
for (i = 0; i < parsedData.predictions.length; i++) {
text += 'Record #' + i + ' = ' + parsedData.predictions[i].t + " " + parsedData.predictions[i].v + " " + parsedData.predictions[i].type + " - ";
let curDateTime = moment().format('LLL');
let theDate = moment(parsedData.predictions[i].t).format('LLL');
let fromNow = moment(parsedData.predictions[i].t).fromNow();
if (parsedData.predictions[i].type === "H") {
console.log('High tide for ' + parsedData.predictions[i].t + ', at ' + parsedData.predictions[i].v + ' vertical Feet. ');
if (moment(theDate).isSameOrBefore(curDateTime)) {
console.log('It is currently ' + curDateTime + ' and that high tide was ' + fromNow);
} else {
console.log('It is currently ' + curDateTime + ' and that high tide is ' + fromNow + ' from now!');
}
} else {
console.log('Low tide for ' + parsedData.predictions[i].t + ', at ' + parsedData.predictions[i].v + ' vertical Feet. ');
if (moment(theDate).isSameOrBefore(curDateTime)) {
console.log('It is currently ' + curDateTime + ' and that low tide was ' + fromNow);
} else {
console.log('It is currently ' + curDateTime + ' and that low tide is ' + fromNow + ' from now!');
}
}
}
}, function(error){
console.log("problem");
});
}
testMod();
我認為部分問題是您正在使用格式化的字符串創建矩實例,而不是僅使用矩實例本身。 所以不要這樣做:
let curDateTime = moment().format('LLL');
let theDate = moment(parsedData.predictions[i].t).format('LLL');
// ...
moment(theDate).isSameOrBefore(curDateTime);
嘗試:
let curDateTime = moment();
let theDate = moment(parsedData.predictions[i].t);
// ...
theDate.isSameOrBefore(curDateTime); // because theDate is now a moment instance, you can call this function on it
在使用矩時,將日期時間存儲為矩實例一直是一個好主意,直到需要將其顯示給用戶為止,然后可以繼續執行以下操作:
theDate.format('LLL');
我認為您收到的警告是因為您正在嘗試創建一個時刻實例,該實例帶有一個'LLL'格式的字符串,該字符串正在引起抱怨(“棄用警告:提供的值未采用公認的RFC2822或ISO格式。”我看到的警告)。 如果要解析這些格式,則還必須指定格式:
moment('September 4, 1986 8:30 PM', 'LLL').format('YYYY-MM-DD H:mm'); // won't complain
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.