在JavaScript (React)中使用date from一个和time from另一个连接moment datet



我有两个Moment DateTime对象,分别称为'date'和'time',每个对象都从Ant Design库的输入字段接收它们的值。我想从一个对象中获取日期,从另一个对象中获取时间,然后将它们组合到一个DateTime对象中。

我试过下面的方法:

moment(date?.get('year') + '-' + date?.get('month') + '-' + date?.get('date') + 'T' + time?.get('hour') + ':' + time?.get('minute')+':00.000Z') //this does not result in a DateTime object
moment(date?.toDate(), time.toTime()) //this was a bit of an experiment. toDate works, but toTime not

我发现了类似的问题,但在这些情况下,他们使用字符串数据而不是DateTime对象,例如:

moment.js连接日期和时间

我当然可以按照这个例子生成一个字符串,这基本上与我在上面的例子中所做的类似。

我觉得我可能把事情复杂化了。有什么简单的方法吗?

如有任何建议,不胜感激

由于datetimeMoment对象,可以直接用time的值设置date的小时和分钟。然后,toDate()为您提供Javascript DateTime对象。我想不出更短的方法了。

const date = moment("2021-10-19", "YYYY-MM-DD"); // date parts, be careful about timezone
const time = moment("10:00", "HH-mm"); // time parts, may be extended with seconds, milliseconds
// Assuming that date or time can be null or undefined below
console.log(date?.format());
console.log(time?.format());
// Let's add hour and minute of time to date
date?.hour(time ? time.hours() : date.hours()).minute(time ? time.minutes() : date.minutes());
console.log(date?.format()); // time of date is set
console.log(date?.toDate()); // Javascript DateTime object
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

相关内容