'From date to day start time and end time in utc in specific timezone using moment

Hi I am trying to find specific date to timezone, based on day start and end time in UTC, using momentJS.

For example: I have one date : 2020-08-17 and its timezone is -5.

I would like to get day start and day end time in utc in this specific timezone.

I tried below code: But if I try other timezone, its always getting same data start and day end time as in utc.

date = 2020-08-21;
timezone=-5;//+10:30, +5:30
var start_date = moment.utc(moment(date).utcOffset(timezone).startOf('day').format()).format();
var end_date = moment.utc(moment(date).utcOffset(timezone).endOf('day').format()).format();

If I am missing anything please suggest,



Solution 1:[1]

I am not sure I understood your question correctly, but it seems like the only problem is that you need to wrap the date in the date variable in quotes because it is supposed to be a string. Otherwise it just subtracts 2020 - 8 - 21 which is 1991.

The code seems to run fine even if you change the timezone:

const moment = require('moment')

var date = "2020-08-21";
var timezone = -5; //+10:30, +5:30
var start_date = 
              moment.utc(
                moment(date)
                  .utcOffset(timezone)
                  .startOf('day')
              ).format("YYYY-MM-DD @ HH:mm:ss");
var end_date = 
              moment.utc(
                moment(date)
                  .utcOffset(timezone)
                  .endOf('day')
              ).format("YYYY-MM-DD @ HH:mm:ss");

console.log(start_date)
console.log(end_date)

Run and edit this code online

Output:

2020-08-20 @ 05:00:00
2020-08-21 @ 04:59:59

If the timezone variable is changed to 0 (UTC time), then the result is:

2020-08-21 @ 00:00:00
2020-08-21 @ 23:59:59

...which is indeed the start and end of the day.

Solution 2:[2]

This should do it.

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();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marsnebulasoup
Solution 2 Bank5z0rSqt