I wants to store work Hours in form of Hours and Minutes format i.e. 4 Hours & 38 Minutes.
I have converted into total minutes by subtracting checkIn time and checkOut(current) time.
Work Hours will be calculated when Employee checkOut.
I am using MongoDB for database.
Let me be more precise, when the employee does the checkout I wants to calculate the total working hours in form of Hour & Minute format
attendanceController.js
-----------------------
exports.checkOutAttendance = catchAsync(async (req, res, next) => {
const employee = await User.findById(req.user?.id);
const currentDate = format(new Date(), "dd-MM-yyyy");
if (!employee) {
return next(new AppError("Employee not found or not LoggedIn", 404));
}
const existingAttendance = await Attendance.findOne({
employee: employee._id,
date: currentDate
});
if (!existingAttendance || !existingAttendance.checkInTime) {
return next(new AppError("You have not checkedIn for today", 400));
}
const checkInTime = existingAttendance.checkInTime;
const checkOutTime = Date.now();
const workHoursMillis = checkOutTime - checkInTime;
const totalMinutes = Math.floor(workHoursMillis / (1000 * 60));
// const totalHours =
const checkedOut = await Attendance.findByIdAndUpdate(existingAttendance._id, {
checkOutTime: checkOutTime,
workMinutes: totalMinutes,
notes: "CheckedOut Successfully"
});
res.status(200).json({
status: 'success',
data: {
data: checkedOut
}
});
});
attendanceModel.js
------------------
const mongoose = require("mongoose")
const attendanceSchema = new mongoose.Schema({
employee: {
type: mongoose.Schema.ObjectId,
ref: "Employee"
},
date: {
type: String,
unique: false
},
checkInTime: {
type: Date
},
checkOutTime: {
type: Date
},
workHours: {
type: Number
},
notes: {
type: String
}
})
const Attendance = mongoose.model("Attendance", attendanceSchema)
module.exports = Attendance
I wants to store the data in form of Hours & Minute format.
Thank you everyone for your time & contribution in advance!!😊
2
Answers
Modify the Attendance Schema
Update the Checkout Function