如何在日期时间中使用时间段

How to use the Time period in date time

我有一个表单可以从输入发送年和月的值,然后在将值发送到服务器时我正在将该值转换为 ISO 字符串,如下所示:

const toIsoString = (year, month, day) => moment(new Date(year, month - 1, day)).toISOString(true).split('.')[0];

然后在我这样使用它的值中。

StartDate: toIsoString(data.StartYear, parseInt(data.StartMonth, 10), 1),

在那种情况下它发送的值是这样的:

startDate: "2021-01-01T00:00:00"

有人知道为什么时间段被忽略吗?我怎样才能发送带有年月日的时间段values.Any帮助很大appreciated.Thanks...

因为你在创建moment对象时只是设置了年月日。你没有设置时间

你应该这样做

const toIsoString = (year, month, day) => {
    const currDate = moment(new Date());
    currDate.year(year);
    currDate.month(month - 1);
    currDate.date(day);
    return currDate.toISOString(true).split('.')[0];
}

或者简单地使用set函数

const toIsoString = (year, month, day) => {
    const currDate = moment(new Date());
    currDate.set({
        'year': year,
        'month': (month - 1),
        'date': day
    });
    return currDate.toISOString(true).split('.')[0];
}

Does anybody know why the Time period is being ignored and how can I also send the time period with the year, month and date values.Any helps would be highly appreciated.

时间没有被忽略。在函数中:

const toIsoString = (year, month, day) => 
  moment(new Date(year, month - 1, day)).toISOString(true).split('.')[0];

小时、分钟、秒和毫秒的值被省略,因此它们默认为 0。您预计几点?

如果你想将当前本地时间添加到日期中,那么创建一个日期并将年月日设置为所需的值而不修改时间(虽然我不知道你为什么要这样做那样做)。

与其创建随后需要进一步处理的字符串,不如告诉 moment.js 您想要的格式:

function toIsoString (year, month, day) { 
  return moment(new Date().setFullYear(year, month-1, day)).format('YYYY-MM-DD HH:mm:ss');
}

console.log(toIsoString('2021','1','1'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>

您也可以在没有库的情况下执行此操作,请参阅 How to format a JavaScript date,例如:

function formatDate(year, month, date) {
  let z = n => (n<10?'0':'') + Number(n);
  return `${year}-${z(month)}-${z(date)} ${
    new Date().toLocaleString('en',{
      hour12:false,
      hour:'2-digit', 
      minute:'2-digit', 
      second:'2-digit'})
  }`;
}

console.log(formatDate('2021','1','01'))