Dayjs - date is different locally compared to running on a hosted server

156 Views Asked by At

I'm formatting a string (in the style 'THU 04 JUL 2024') to a date string, and I'm then using that date in a query to a database.

This is the code:

const groupDate = "THU 04 JUL 2024"
const myDate = dayjs(groupDate, 'Do MMM YYYY').format() 
// local server output: 2024-07-04T00:00:00+01:00 (correct) 
// production server output: 2024-07-04T00:00:00+00:00 (incorrect)

I need it to use the London time zone, based on whether the date is BST or GMT (e.g, a date in July would be +1, a date in January would be +0).

I've tried using the utc and timezone plugins, but it converts the date to 11pm the day before, e.g. dayjs(myDate, 'Do MMM YYYY').utc().format() // 2024-07-03T23:00:00Z

Any help here would be great, thank you

EDIT

Solved thanks to the help of @Spender in the comments for getting me on the right path. The issue is because "THU 04 JUL 2024" in London occurs at 2024-07-03T23:00:00Z when converted to UTC.

Below is the working code:

const dayjs = require('dayjs')
const utc = require("dayjs/plugin/utc")
dayjs.extend(utc)
----
const groupDate = "THU 04 JUL 2024"
const myDate = dayjs(groupDate, 'Do MMM YYYY').format();

 
const _utcOffset = myDate.slice(-6); // gets the offset in time from utc

dayjs(myDate).utcOffset(_utcOffset).format() // formats it, ignoring the original offset

I probably haven't explained this well, but it works.

0

There are 0 best solutions below