英文:
convert time to Date type nest js
问题
在上面的代码中,data.Intime
是一个表示时间的字符串(例如:"00:39:41"),而 attendance.date
是一个 Date 类型的变量。您可以使用以下方法将 data.Intime
转换为 Date 类型:
// 将 data.Intime 字符串解析为 Date 对象
attendance.date = new Date(`1970-01-01T${data.Intime}Z`);
这里我们将data.Intime
字符串与日期字符串("1970-01-01T")组合,然后将其传递给 Date
构造函数来创建一个包含日期和时间信息的 Date 对象。最终的 Date 对象将包含正确的日期和时间信息,可以用于赋值给 attendance.date
变量。
英文:
@Cron('23 16 * * *')
async transferData() {
try {
// Retrieve data from the AttendanceBulk table
const attendanceBulkData = await this.AttendanceBulkModel.findAll();
for (const data of attendanceBulkData) {
const attendance = new Attendance();
// Find the corresponding AttendanceAndBulk entry based on data.UserId
const attendanceAndBulk = await AttendanceAndBulk.findOne({ where: { UserId: data.UserId } });
if (attendanceAndBulk) {
attendance.employeeId = attendanceAndBulk.employeeId;
attendance.shiftType = data.Intime ? ShiftType.In : ShiftType.Out;
attendance.time = new Date(`${data.Intime}`);;
attendance.date = data.Date;
attendance.outTime= data.Date;
console.log(data.Intime)
await attendance.save();
}
}
this.logger.log('Data transfer completed successfully.');
} catch (error) {
this.logger.error('Data transfer failed:', error);
}
}
In above code I data.Intime is comming like 00:39:41 this. but attendance.date variable is Date type. how can I convert time varibale(00:39:41) to Date type in nest js?
答案1
得分: 1
只返回翻译好的部分:
你只接收小时/分钟/秒钟
这不足以创建一个日期
一个可能有效的解决方案是创建当天的日期,然后将接收到的时间设置在这个日期上
const [hours, minutes, seconds] = date.InTime.split(':');
const timestamp = (new Date()).setHours(hours, minutes, seconds);
const date = new Date(timestamp);
这是关于Date对象的文档链接,我们从中调用setHours方法
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours
如果您计划大量使用日期,我还建议查看dayjs,这是一个非常方便的JavaScript日期操作库
https://day.js.org/
英文:
You are only receiving hour/minutes/secondes
This is not sufficient to create a date
A solution that might work would be to create the date of the day, and then set the received time on this date
const [hours, minutes, seconds] = date.InTime.split(':');
const timestamp = (new Date()).setHours(hours, minutes, seconds);
const date = new Date(timestamp);
Here is the link of the documentation for the Date object, from wich we call the setHours methods
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours
If you plan on working with date a lot, i would also advise to checkout dayjs, a very convenient library for date manipulation in javascript
https://day.js.org/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论