我目前从日历控件获取日期,并使用 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());
Run Code Online (Sandbox Code Playgroud)
目前 formattedDateParsed 为“Null”
我能得到一些关于如何解析日期以便计算差异的帮助吗
这里发生了一些事情。
首先,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);
Run Code Online (Sandbox Code Playgroud)
其次,您要转换为字符串,然后再转换回 DateTime,使用 Date 构造函数作为解析器,这不是一个好主意,因为 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}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9025 次 |
| 最近记录: |