Date format on client browser - javascript

I am getting a date from the server as a javascript string(GMT) or unix timestamp(GMT).
I can convert it to a javascript date object with
var date = new Date(string) or var date = new Date(string)
This gives me the date variable with proper system time-zone's time.
Currently I am displaying this- date.toLocaleString()
Which gives me a nicely formatted date/time according to my system locale and time zone.
I am using this to automatically accomodate for DST if the client browser follows it.
Previously I was required to display this date only in EST, but when the US time started following EDT, I was told to display it in EST. I think this approach would simplify displaying the time/date acoording to user's system time setting.
Is there any disadvantage or possible bug accociated with this approach?
If yes, what would be the best way to display this date in the browser, so that it displays correctly according to the timezone(accomodating DST if any) in which the user(cient browser) is?

As pointed out in the comments, the output may be different depending on the users settings. A more reliable and flexibe solution is moment.js, which is a great library.
moment("2013-04-04", "YYYY-MM-DD").format("MMM Do YY"); //"Apr 4th 13"

Related

Is there a way to override `new Date()` in Javascript so it always returns the date considering one specific hardcoded timezone?

I'm working on a React.js project that handles lots of comparisons related to DateTime (comparing the hour, the month, the year and so forth to dates retrieved from an API). For this specific React.js application, I would like to always consider DateTimes (from new Date()) as if the user was in the server timezone. Assuming that the server is in "Europe/Berlin" timezone, I would like that at any point in the application, calling new Date('2019-01-01') would retrieve me a DateTime that refers to this time in the "Europe/Berlin" timezone, that would be Tue Jan 01 2019 01:00:00 GMT+0100 (Central European Standard Time). If I set my computer Date and Time as if I was in Brazil, for instance, I get Mon Dec 31 2018 22:00:00 GMT-0200 (Brasilia Summer Time), but would like to get the same as before. The main reason why this is a problem is that we extract data from these DateTimes such as .getHours(), .getDate(), etc.
This would fit this specific application because it's really important for this project that we only support the server Timezone, no matter where the user is. So to keep consistent with the server time, the call new Date('2019-01-01').getDate() should return 1, since it will be 1st January in Berlin. However, if the user is in Brazil, this same call will return 31, as Brazil is some hours before GMT, when it's midnight in GMT time, it will be still the previous day in Brazil.
I tried first to use the date-fns along with date-fns-timezone to set the DateTime to display the dates and times to the client considering the server timezone. That worked fine to display the right data but didn't solve some issues that are caused due to these attributes extraction from the date and that will vary depending on where the user is.
So that's why what I'm trying to do now is override the new Date() method in a way that it will always retrieve the date as if the user was in the server time. I haven't managed to get how it can be done. Whenever I change the Date and Time from my computer, the output for the new Date() already takes into account this new date and time settings.
So how can I force the new Date() to always give back the DateTime with a hardcoded timezone? Also, it would be really good if I could do it without using external libs (like moment.js, for instance), and do it only with plain Javascript.
I was taking a look into the window.navigator variable to see if I could set this one to force the Date to the server timezone, but it doesn't look like that will be the way to solve my issue.
I looked a lot for this answer and didn't find any question that was really close to this one. I'll just list here some of the questions I looked before and why my case differs from them.
1- new Date() for a specific timezone in JavaScript: In this case, the moment is used, and there was no way to accomplish this overriding for the new Date() itself.
2- Convert string to date without considering timezone: In this one, the answer gives back a string with the date formatted to the desired timezone, but not a Date object itself.
3- javascript date considering Request.UserLanguages[0]: also in this one, the question/answer is about formatting the date output rather than retrieving the Date object itself with the new timezone.
4- How do I combine moment.js timezone with toDate to build a new date object?: in this one the answer also is about using moment.js, what I would like to avoid since what I really want to achieve is overriding the new Date() method.
A few things:
Generally speaking, one should try to design their applications such that the server's time zone is not relevant at all. This means only relying on the server's UTC functionality, and working with specific named time zones. Asking for the local time of a server tends to become problematic, especially when dealing with environments where you may not have full control of the server.
Keep in mind that the Date object in JavaScript is misnamed. It is really a timestamp. Essentially it is just an object wrapper around the value you get with .valueOf() or .getTime() or when you coerce it to a number. Everything function on the Date object simply reads this value, applies some logic (which may or may not use the local time zone depending on the function), and emits some result. Similarly, the constructors of the Date object interpret your input and then assign this number in the resulting object. In other words, the Date object does not keep track of a time zone at all. It simply applies it when it is called for. Thus, one cannot change it.
When you pass a string in yyyy-MM-dd format to the Date constructor, per the ECMAScript specification it is interpreted as midnight UTC, not as midnight local time. This is a deviation from ISO 8601, and such often confuses people.
The strings you showed as output like Tue Jan 01 2019 01:00:00 GMT+0100 (Central European Standard Time) are emitted in local time, and are the result of either calling the .toString() function, or by passing a Date object to console.log in some environments. Other environments show the result of .toISOString(), which is emitted in UTC.
There's no global in window.navigator or elsewhere that can change the local time zone. In Node.js apps, if you really need to set the server's time zone globally, you can set the TZ environment variable before launching Node. However, this doesn't work in Windows environments, and doesn't help for browsers.
You're on track with using a library such as date-fns with date-fns-timezone. There are other libraries as well, which are listed in this answer. Alternatively, you could call .toLocaleString with the timeZone option, such as:
new Date().toLocaleString("en-US", {timeZone: "America/New_York"})
This API provides functionality for emitting a string in a particular time zone, but it does not do anything for applying a time zone to an input string.
So ultimately, to answer your question:
So how can I force the new Date() to always give back the DateTime with a hardcoded timezone?
Sorry, you can't. You can either use a different object to track the time zone statefully, or you can use functions that take the time zone as a parameter. Both are things offered by existing library, but only the one function I showed above is currently built in to JavaScript.
In case someone else has this same problem, here is the approach that I followed to solve the issue:
As in this specific case I really need to compare and group some entities based on date, among other operations (always considering the server timezone), I ended up choosing moment.js along with moment-timezone. The native Date class would not solve it since it has no way to handle different timezones. Then, I tried to use first date-fns and date-fsn-timezone, but as these libs always use the standard Date class, it gets back to the problem that a Date in javascript is only a timestamp and has no clue about other timezones other than the one in the client (the application is a React.js one).
Just to show one example about the issue, consider that the server is placed in Europe/Berlin timezone, and one stamp is retrieved as 2019-04-30T02:00:00+02:00. On the React.js application, I want to group this stamp to all the stamps that are also from 2019-04-30. However, if the browser is in Brazil/Brasilia time, the call new Date('2019-04-30T02:00:00+02:00').getDate() will give me 29 as return, since in the client timezone, this same timestamp will represent 2019-04-29T09:00:00-03:00.
Using moment and moment-timezone it could be fixed by defining in which timezone I want to retrieve the values, such as:
moment('2019-04-30T02:00:00+02:00').tz('Europe/Berlin').date()
// retrieves 30 independent on the client timezone.
Thank you very much to all who contributed with answers and suggestions. You all helped me to find the path to solve this issue.

Using moment.js, can my date or my date timezone change if I use a VPN?

I'm new with javascript and I am using moment.js.
My code is const date = moment().
Let's supposed one of my website's user (A) is using a VPN, locating him to an area using a different timezone. The other user (B) is using the website in the same country but with no VPN.
Will the value of date be different for the two users, and will it's timezone be the same?
Thanks in advance!
Not necessarily, although it has nothing to do with the IP address/VPN usage.
The date, time and timezone that new Date() will give is entirely dependant on the host OS configuration. There's even no way you can guarantee that 2 machines on the same network have the same/different time or date.

DateTime.Min JSON Serialisation Incorrect

I am trying to figure this strange behaviour on a client machine (IE10)
When we create a new javascript Object, the ajax response from the server is \/Date(-62135596800000)\/.
I format the JSON Date in the following way:
var date = new moment(parseInt(response.substr(6)));
On the Client machine this Date Object returns the following Date Format 0000-12-31.
When I try to validate the Date on the Server I get the response is an error saying that this is not a valid date.
My validation is Fluent Validation and the Rule is
RuleFor(x=>x.LastUpdateDate).NotEmpty();
Can anyone point me in the correct direction to help solve this issue?
Your timestamp value is interpreted as being an offset from a fixed UTC reference point. However, when you do something like
alert(theDate)
you'll see the default rendition of the Date instance as it would appear in the local time zone. In other words, a computer in Hong Kong will show the same UTC date differently than a computer in London.
You can use
alert(theDate.toUTCString())
to see a UTC version of the date.

Change timezone in Arshaw FullCalendar

From my understanding, Arshaw FullCalendar displays events according to the timezone of the local computer's operating system. I assume this is done by the javascript Date() object, which also is based on the local computer's operating system. I have an application that has group calendars and a group timezone, I want to be able to force every local Arshaw Calendar to display according to that group's time-zone, no matter what timezone that computer is. How do you do this?
Note: I've looked through the documentation fairly thoroughly, and found no such option. I'm hoping that javascript has something equivalent to php's date_default_timezone_set(), which seems to me the way this could be solved.
*Edit 1/31/2013 12:23pm CST:
I am sending everything to the calendar as unix timestamps, so I assume the option ignoreTimezone would not apply here, as described in this stackoverflow thread:
jQuery FullCalendar timezone synchronization
You should probably try to set the option "ignoreTimezone" to "false" and give to Arshaw FullCalendar date in ISO8601.
You can get more information about that here: http://arshaw.com/fullcalendar/docs/event_data/ignoreTimezone/
To convert unix timestamps to ISO8601, you can use this in javascript:
var d = new Date(1360412434000).toISOString();
This is ECMAScript 5.
See here for compatibility and fallback code: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toISOString

Identifying the date format in the client's machine

I have a requirement in my project to show a date in the client machine format. I am aware of the property in javascript window.navigator.userLanguage or window.navigator.language.. But it is only returning the language of the client machine like 'en-US', 'en-GB' etc.
If the user customizes the date format of the machine for eg:-dd-MMM-yyyy, is there any way to get that format in Javascript?
Thanks in advance
suhaib
You can use the .toLocaleDateString() method:
var yourDate = new Date();
alert(yourDate.toLocaleDateString());
This doesn't tell your code what the user's selected date format is, but it lets you display a date in whatever the user's format is.
On my PC the above alerts "Tuesday, 26 June 2012".
The .toLocaleTimeString() method does the equivalent thing for the time.
The .toLocaleString() method displays date and time.

Categories

Resources