Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing a date in JavaScript when timezone is irrelevant

I am working on a very small JavaScript library that allows users to retrieve content based on date. For this content, the date is just an identifier and timezones are completely irrelevant (think along the lines of a Dilbert flip calendar). The "May 14th" content is the same whether you are in the United States or Australia.

The function for retrieving data currently takes a Date object as a parameter. Within the function, the timezone is ignored. Does this approach make sense, or would it be better to take a timezone-independent identifier (like 2012-01-01) as a parameter instead? With the Date object approach, do I run the risk of returning the wrong data as a result of timezone adjustments browsers make?

like image 951
John Karahalis Avatar asked Apr 29 '26 04:04

John Karahalis


2 Answers

How about using Date.getUTC*() functions? UTC time is the same for everyone.

like image 120
parnas Avatar answered May 01 '26 16:05

parnas


After doing some research, it appears that simply ignoring the timezone information is the best approach. Why? This will always preserve the date and time that were provided to the Date constructor (which is my goal), whereas the getUTC* methods will return altered versions of the date and time. For example, take a look at this node REPL session I ran on a computer in the Eastern Time zone.

> d = new Date(2013, 03, 27, 23, 00, 00)
Sat Apr 27 2013 23:00:00 GMT-0400 (EDT)
> d.getDate() // The same date provided in the constructor. Woo!
27
> d.getUTCDate() // A different date. Boo!
28

Long story short, if you want to read the exact date and time that were provided in the Date constructor, using the normal get* methods (like getDate) will do that. If you use the getUTC* methods (like getUTCDate) modified versions of the date and time will be returned.

I know this may sound rudimentary to some of the more experienced programmers out there, but this really helped me make sense of things. I hope it helps others who come along.

like image 39
John Karahalis Avatar answered May 01 '26 16:05

John Karahalis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!