I have a function where I convert a date string or a datetime string into a date object with time set to 00:00:00
- basically truncating the time.
/**
* @param dateString - can either be 2023-07-13 or 2023-07-13 03:03:03
*/
const removeTime = (dateString: string): Date | undefined => {
if (isValid(new Date(dateString))) {
const timestamp = new Date(dateString);
console.log('PARAM', dateString);
console.log('NATIVE', timestamp);
console.log('BEFORE TRUNCATE', format(timestamp, Constants.FORMAT_DATE));
console.log(
'AFTER TRUNCATE',
format(
new Date(timestamp.getFullYear(), timestamp.getMonth(), timestamp.getDate()),
Constants.FORMAT_DATE
)
);
return new Date(timestamp.getFullYear(), timestamp.getMonth(), timestamp.getDate());
} else {
return undefined;
}
};
Please note that both the isValid
and format
calls are coming in from date-fns.
My problem is that the new Date(dateString)
call sets the day back by 1.
PARAM: 2023-07-13
NATIVE: Wed Jul 12 2023 18:00:00 GMT-0600 (Mountain Daylight Time)
BEFORE TRUNCATE: 2023-07-12
AFTER TRUNCATE: 2023-07-12
My Constants.FORMAT_DATE
is yyyy-MM-dd
.
It looks like this is only an issue if the dateString
doesn't have a time part to it (i.e. 2023-07-13
). The function actually works just fine if the string contains a time (i.e. 2023-07-13 03:03:03
).
PARAM: 2023-07-13 11:26:11
NATIVE: Thu Jul 13 2023 11:26:11 GMT-0600 (Mountain Daylight Time)
BEFORE TRUNCATE: 2023-07-13
AFTER TRUNCATE: 2023-07-13
You should add the timezone offset:
const isValid = dt => !isNaN(+dt);
const removeTime = (dateString) => {
const dt = new Date(dateString);
if (!isValid(dt )) {
return;
}
dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
return new Date(dt.getFullYear(), dt.getMonth(), dt.getDate());
};
console.log(removeTime('2023-07-13').toString());
console.log(removeTime('2023-07-13 03:03:03').toString());