javascript - 如何在 Luxon 中使用 diff 方法
问题描述
我目前从日历控件中获取日期,并使用 luxon 添加天数、分钟数并将其更改为 LongHours 格式,如下所示: newValue : is value I get from frontend(calendar control)
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”的形式出现
我可以就如何解析日期获得一些帮助,以便可以计算差异
解决方案
这里发生了一些事情。
首先,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);
其次,您要转换为字符串,然后再转换回 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}
推荐阅读
- javascript - Javascript 事件/序列问题:为什么这个事件会触发?
- javascript - Javascript:从 x-www-form-urlencoded 请求中获取参数值
- swift - SKPhysicsContactDelegate,碰撞无法正常工作
- python - 如何从某个日期获取某个单词的TF-IDF?
- java - java内部类中静态成员的使用
- c++ - Counting function arguments at compile time
- vb6 - 设置系统日期需要提升权限吗?(错误 70 权限被拒绝)
- javascript - 我可以在 Django 框架中使用 jQuery
- python - 如何优化当前使用列和行迭代完成的 python 数据帧上的多个操作?
- python - 过滤整个相关矩阵的值