Moment.js startOf is returning end of day

Viewed 2347

I am passing in the following date through query string: 2020-09-23

I am trying to figure out why the below code with the doesn't work comment above it is not working.

// If figure here I should only have to convert to a moment once
const momentDate = moment.utc(req.query.dateTime);

// Doesn't work
const startOfDay = momentDate.startOf('day');
const endOfDay = momentDate.endOf('day');

This is what I am getting:
console.log(startOfDay) = Moment<2020-09-23T23:59:59Z>
console.log(endOfDay) = Moment<2020-09-23T23:59:59Z>

// Works (when I directly pass in the query string param)
const startOfDay = moment.utc(req.query.dateTime).startOf('day');
const endOfDay = moment.utc(req.query.dateTime).endOf('day');

console.log(startOfDay) = Moment<2020-09-23T00:00:00Z>
console.log(endOfDay) = Moment<2020-09-23T23:59:59Z>

2 Answers

You are doing on the same object momentDate, so same reference, so the safer way is to work on the copy of that object by cloning that momentDate with clone() method

const momentDate = moment.utc(new Date())

const startOfDay = momentDate.clone().startOf("day")
const endOfDay = momentDate.clone().endOf("day")

console.log(startOfDay)
console.log(endOfDay)

If you have a timezone problem, try this approach.

let myDate = new Date();

const timezoneOffset = moment(myDate).utcOffset();

moment(myDate).utc().add(timezoneOffset, 'minutes').startOf('day').format();
moment(myDate).utc().add(timezoneOffset, 'minutes').endOf('day').format();
Related