0

I am getting confused with javascript dates but within my app, I am using the following npm package: rc-datepicker

Here the user clicks on a date, which is 21/11/2021 but for some reason, within state, it is being stored as:

2021-11-20T23:25:43.223Z

which is the day prior.

I have got a console log of the date that is being passed through, which is in the following format:

Sun Nov 21 2021 10:25:46 GMT+1100 (Australian Eastern Daylight Time)

Can someone pls assist on how to ensure that the 21/11/2021 is returned and ignore the timezone, if that is the issue or something else?

3
  • +1100 It's simply UTC vs local time (but the same moment in time) Commented Nov 29, 2021 at 23:40
  • @pilchard - based on this as I am confused, can you pls let me know what I need to apply/do, to obtain the actual date selected as I need to store this 21/11/2021 within the backend DB? Commented Nov 29, 2021 at 23:45
  • If you just want to store the string you can output it from the returned date before storing date.toLocaleDateString('en-GB') see: Date.prototype.toLocaleDateString(). Keep in mind that without explicitly providing a timezone it will use the timezone of the users local machine. Commented Nov 29, 2021 at 23:50

1 Answer 1

1

Because you are on AEDT (me too!) your dates will show in your timezone.

As pilchard mentioned in the comment, 2021-11-20T23:25:43.223Z is GMT so that's like the start point. Us being +11 means those two representations of time above are actually at the same point in time.

Let's look at what happens with those dates you have.

If you call:

const d = new Date("2021-11-20T23:25:43.223Z")
console.log(d.toString()) // Prints the local representation: Sun Nov 21 2021 10:25:43 GMT+1100 (Australian Eastern Daylight Time)

console.log(d.toISOString()) // Prints in ISO formatted string

Have a look at other date object methods.

So store that string (eg. "2021-11-20T23:25:43.223Z") which represents the same point in time anywhere in the world. Then convert it to the user's local timezone

const d = new Date("2021-11-20T23:25:43.223Z")

You can use other methods such as toLocaleDateString in the link above to specify a particular timezone. The timezone component can be one from the tz database. There is a list of them on wikipedia.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.