I have the following date with time info within my JavaScript app:
"startDate": "2021-05-25T09:50:40.603Z"
"startTime": "2021-05-12T11:52:40.603Z"
What I need to achieve is to create a new variable that takes the date portion only of "startDate" and combine it with the time portion of "startTime", i.e.
2021-05-25 + T11:52:40.603Z = 2021-05-25T11:52:40.603Z
I was looking at using date-fns format to perform the above split but unsure how to combine it again as I need to ensure that the new combined date and time is still a JavaScript date object as above.
Assuming your dates are in the ISO format and need another ISO date string as the result:
function start (date, time) {
return `${date.split("T")[0]}T${time.split("T")[1]}`;
}
console.log(start("2021-05-25T09:50:40.603Z", "2021-05-12T11:52:40.603Z"));
In the ISO format, the date is separated from the time using the letter T
(for "time"). My function splits both dates at that point. For the date, we use [0]
(before T) and the time is [1]
(after the T). The Z
(Zulu) at the end stands for Zulu Time which is the same as UTC. More about this format on Wikipedia.
When storing dates and times in JavaScript, I would highly recommend using UNIX timestamps, which is a number representing the milliseconds past after the beginning of the UNIX epoch (Jan 1 1970). These timestamps can easily be converted to date objects in most programming languages and platforms. Here is the same function, but using UNIX timestamps and the JavaScript date object.
function start (date, time) {
return new Date(`${new Date(date).toDateString()} ${new Date(time).toTimeString()}`)
}
console.log(start(1621936240603, 1620820360603));
// this function will also recognise strings
console.log(start("25 May 2020", "Feb 13 2019 9:00 AM UTC"));