我目前从日历控件中获取日期,并使用luxon添加天、分钟,并将其更改为LongHours格式,如下所示: newValue :是我从前端(日历控件)获取的值
let formattedDate: any;
FormattedDate = DateTime.fromJSDate(new Date(newValue)).plus({ days: 1, hours: 3, minutes: 13, seconds: 10 }).toLocaleString(DateTime.DATETIME_HUGE_WITH_SECONDS)
console.log(formattedDate);
const formattedDateParsed = DateTime.fromJSDate(new Date(formattedDate));
const newValueParsed = DateTime.fromJSDate(new Date(newValue));
var diffInMonths = formattedDateParsed.diff(newValueParsed, ['months', 'days', 'hours', 'minutes', 'seconds']);
diffInMonths.toObject(); //=> { months: 1 }
console.log(diffInMonths.toObject());当前formattedDateParsed以“Null”的形式出现
我能否获得一些帮助,了解如何解析日期,以便计算出差异
发布于 2019-08-13 14:32:01
这里发生了一些事情。
首先,FormattedDate和formattedDate是不同的变量,所以没有设置formattedDate:
let formattedDate: any;
FormattedDate = DateTime.fromJSDate(new Date(newValue)).plus({ days: 1, hours: 3, minutes: 13, seconds: 10 }).toLocaleString(DateTime.DATETIME_HUGE_WITH_SECONDS)
console.log(formattedDate);其次,使用Date构造函数作为解析器,将字符串转换为字符串,然后再转换回DateTime,这不是一个好主意,因为a)这是不必要的,b)浏览器对于它们可以解析的字符串不是超级一致的。
相反,让我们只转换一次:
const newValueParsed = DateTime.fromJSDate(new Date(newValue));
const laterDate = newValueParsed.plus({ days: 1, hours: 3, minutes: 13, seconds: 10 });
const diffInMonths = laterDate.diff(newValueParsed, ['months', 'days', 'hours', 'minutes', 'seconds']);
diffInMonths.toObject(); // => {months: 0, days: 1, hours: 3, minutes: 13, seconds: 10}https://stackoverflow.com/questions/57423531
复制相似问题