2

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)
  • 1
    Keep in mind that the start of the day is not *always* midnight. In some time zones, on the day DST starts, the start of day is `01:00`. – Matt Johnson-Pint Jan 27 '23 at 23:50
  • And then, mainly for the purposes of driving terror into the hearts of programmers, some local days start twice. They pass the first midnight, briefly jump back to yesterday, and then pass through midnight a second time, typically (but not always of course) an hour later. – Howard Hinnant Jan 28 '23 at 19:04

2 Answers2

2

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

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