简体   繁体   中英

Javascript date object UTC instead of user timezone

I am trying to collect input from a user and pass it to a server in order to query for available results in the database. My issue is that because there is a time input, the timezone effects the query and is returning null, eg 6/1/21 = 1622505600000, but 6/1/21 at user timezone might be 1622527200000.

I have parsed the input from the react native frontend using the following code

console.log(new Date(selectedDate.getUTCFullYear(), (selectedDate.getUTCMonth()), (selectedDate.getUTCDate()),0,0,0,0))

the output of which in this example is 2021-06-01T06:00:00.000Z

Why is the 6 hour delay being added despite the fact that I'm setting all 0 hr, min, sec, ms?

Figured it out.

The date constructor is working from the local timezone and is taking raw inputs to create the date in the local timezone. When I was running

new Date(2021,5,1,0,0,0,0)

it was creating that date in the devices local time, then sending to the server. what I needed to do was

new Date(newDate.getUTCFullYear(), (newDate.getUTCMonth()), (newDate.getUTCDate()),0,0,0,0).getTime() - (newDate.getTimezoneOffset() * 60000)

in order to create the date, THEN take away the timezone offset.

edit: the 60,000 offset isn't the amount of offset, it's to get the minutes into milliseconds for the timecode. the offset is automatically calculated using the getTimezoneOffset() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM