How to get a start of day date in specific timezone

534 Views Asked by At

I am working with Date Picker component and I am trying to get selected day from date picker to be start of day (midnight) in specific timezone (e.g. Europe/London). So for example if I select 2023-01-30 I want to get something like

Mon Jan 30 2023 00:00:00 GMT (London UK)

Currently output shows my local timezone at the end GMT-0500 (Eastern Standard Time) but I would like to have London one GMT

I am using date-fns to get startOfDay

const d = '2023-01-30';
const [year, month, day] = d.split('-');
const y = startOfDay(new Date(year, month - 1, day));
console.log(' ~ file: ScheduleSection.js:102 ~ convertDateToUtc ~ y', y);

Actual Output: Mon Jan 30 2023 00:00:00 GMT-0500 (Eastern Standard Time)

Expected Output: Mon Jan 30 2023 00:00:00 GMT (London UK)
2

There are 2 best solutions below

0
On BEST ANSWER

Since you have tags for date-fns and date-fns-tz, you can do what you want with those libraries. The following can be run at RunKit.com:

var dateFns = require('date-fns');
var dateFnsTz = require('date-fns-tz');

let date = '2014-06-25T00:00:00';
let timeZone = 'America/Los_Angeles';

// Parse timestamp for America/Los_Angeles
let utcDate = dateFnsTz.zonedTimeToUtc(date, timeZone);

// UTC equivalent: "2014-06-25T07:00:00.000Z"
console.log(utcDate.toISOString());

// Europe/London equivalent: "2014-06-25 08:00:00 GMT+1"
console.log(dateFnsTz.formatInTimeZone(utcDate,
            'Europe/London', 'yyyy-MM-dd HH:mm:ss zzz'));

As RunKit doesn't support import, require is used instead.

0
On

you can use the moment-timezone library, you can install it by running

npm install moment-timezone

in your project's root directory.

Example:

const moment = require('moment-timezone');
const d = '2023-01-30';
const date = moment.tz(d, 'Europe/London').startOf('day').format();
console.log(date);