Wrap Current Time
Transfer the current time to any date object without dealing with complex calendars
Overview
The wrapCurrentTime
function preserves the original date portion while applying the current time to each date. It works with both single dates and arrays of dates.
Usage Examples
Single Date
// Apply current time to a single date
const date = new Date('2023-09-15') // Date at midnight
const dateWithCurrentTime = wrapCurrentTime(date)
// Result: 2023-09-15 with current time (e.g., 15:30:45.123)
Multiple Dates
// Apply current time to multiple dates
const dates = [
new Date('2023-09-15'),
new Date('2023-09-16'),
new Date('2023-09-17')
]
const datesWithCurrentTime = wrapCurrentTime(dates)
// Result: All dates with the same current time
Implementation
wrapCurrentTime.ts
import moment from 'moment'
import _ from 'lodash'
export default function wrapCurrentTime(dates: Date | Date[]): Date | Date[] {
// Check type of dates
let arrDates = _.isArray(dates) ? dates : [dates]
let newDates: Date[] = []
arrDates.forEach(date => {
const currentDate = moment()
let newDate = moment(date)
newDate.hour(currentDate.hour())
newDate.minute(currentDate.minute())
newDate.second(currentDate.second())
newDate.millisecond(currentDate.millisecond())
newDates.push(newDate.toDate())
})
return _.isArray(dates) ? newDates : newDates[0]
}
This implementation automatically handles both date objects and arrays, making it flexible for various use cases.