将日期转换为可以使用moment.js发送到数据库的良好格式



我很难将日期格式转换为可以发送到数据库的好格式。默认情况下,我在dateTimePicker中设置了当天上午08:00。当我想发送它时,它的格式如下"2020-12-01T07:00:00.812Z"。我试图实现的是"2020-12-01 08-00",所以不仅格式不好,而且距离所选时间还有一个小时。我试着用moment.js转换,但什么也没发生。这是我尝试过的代码:

// form where I can pick the date //
ngOnInit() {
this.data= this.formBuilder.group({
id: [],
dateFrom: [this.setTime(), Validators.required],
dateTo: [this.getNextWeek(), Validators.required],
status: [-1],
});
}
// function where I try to convert the date to a useable form //
dataModify(object) {
let formattedObject = {
id: "",
dateFrom: object.dateFrom,
dateTo: object.dateTo,
status: object.status,
};
moment.utc(object.dateFrom).format('YYYY-MM-DD HH:mm');
moment.utc(object.dateTo).format('YYYY-MM-DD HH:mm');
return formattedObject;
}

一般来说,您希望将数据库中的时间保存为UTC,然后根据需要进行转换(通常是客户端(。

根据你的问题,我猜你在GMT+1。您可以手动进行转换,或者添加即时时区:

https://www.npmjs.com/package/moment-timezone

然后你这样转换:

// Change 'Europe/Madrid' to whatever timezone  you need
moment(object.dateFrom).tz('Europe/Madrid').format('YYYY-MM-DD HH:mm'))

好的是,如果你最终不得不为多个时区服务,你可以将所有时间存储在UTC中,然后在必要的地方转换

很抱歉,不需要momentjs来格式化日期。你可以用这个。

formatDate = (date) => {
const _date = new Date(date);
const day = _date.getDate();
const month = _date.getMonth() + 1;
const year = _date.getFullYear();
return `${year}-${month}-${day}`;
}
formatTime = (date) => {
const _date = new Date(date);
const hours = _date.getHours()
const minutes = _date.getMinutes();
const seconds = _date.getSeconds();
return `${hours}:${minutes}:${seconds}`;
}
toDateTimestamp = (date) => {
const dateStamp = this.formatDate(date);
const timeStamp = this.formatTime(date);
return `${dateStamp} ${timeStamp}`
}

最新更新