首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Luxon中使用diff方法

如何在Luxon中使用diff方法
EN

Stack Overflow用户
提问于 2019-08-09 12:32:18
回答 1查看 10.6K关注 0票数 6

我目前从日历控件中获取日期,并使用luxon添加天、分钟,并将其更改为LongHours格式,如下所示: newValue :是我从前端(日历控件)获取的值

代码语言:javascript
复制
  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”的形式出现

我能否获得一些帮助,了解如何解析日期,以便计算出差异

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-13 14:32:01

这里发生了一些事情。

首先,FormattedDateformattedDate是不同的变量,所以没有设置formattedDate

代码语言:javascript
复制
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)浏览器对于它们可以解析的字符串不是超级一致的。

相反,让我们只转换一次:

代码语言:javascript
复制
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}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57423531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档