Weird format Date to `toLocaleString` in javascript - javascript

I have an app that is currently running in Production. Suddenly, I have experienced a weird issue that I am not able to figure it out to prevent it. Any suggestion is highly appreciate.
This is the function where the error happened:
date_time: new Date(
this.selectedDate.getFullYear(),
this.selectedDate.getMonth(),
this.selectedDate.getDate(),
this.selectedHour.value.split(':')[0],
this.selectedHour.value.split(':')[1],
0
).toLocaleString(),
This date_time will be saved in database.
Output Example: 12/9/2021, 2:00:00 PM. Everything is working as expected.
However, today there is new record in database with different format: 12/9/2021 2:00:00 p.m. And it messed up my app. Do you know what happen to toLocaleString() ? Thank you.

Since you tagged this angular I assume this code is running client-side and sending the resulting string to the server for insertion into your database.
toLocaleString converts a date to a string formatted for the user's locale.
It is designed to display a human readable date.
If a user with their system set to a different locale (likely because they are from a different country to you) then it will give different results.
If you want a standard date in a format that is easily machine processable (i.e. good for storing in a database) then use toISOString.
You can parse it and convert it to a local string for display later.

Related

Universal DateTime Format

I'm working on an application where I'm sending datetime from JavaScript (client side) to a Web Service (server side). Now problem with DateTime is it has many formats and at any instance client might have a different format of DateTime than of server, which might break the parsing of datetime on server side.
I was thinking may be JavaScript's function "getTime()" will be an equivalent of C#'s datetime property "Ticks", so that I can sent getTime() from front end and can easily parse it to valid DateTime on server end. But unfortunately that doesn't seems to be the case :(
So is there any universal format that I can use for DateTime that would take my worries away of client's format being different and server responding with 500?
UPDATE
I can get into practice of sending "YYYY-MM-DD" or any other pre-defined format from front end and parse accordingly on back end, but it's viable only till someone misses it, and as a project gets bigger and more devs starts working on it, practices like this becomes overhead on management. So in short it is a work around but not a bull's eye solution. Thanks Mohit for bringing it up I forgot to mention.
I'd suggest the following:
Use JavaScript UTC clientside to send up to the server http://www.w3schools.com/jsref/jsref_utc.asp Or use a date format that cannot be confused (i.e. Long date or "yyyy-MM-dd")
On the server store the dates in UTC
When sending dates clientside send UTC dates to the client and use a JavaScript library like http://momentjs.com/ to render dates clientside in the client's time zone.
in my option , this is not pertain to time format or team convention or other something .
The real question is why you handle time with "String" , not "Date",
you get a Date object ,and turn it to String object , do some operation with string(what is boring and dangerous),and then turn it as Date() (or DateTime in C#) back .
string is string , time object is time object .
the only moment we do date=>string action is showing to end user , as possible as,we handle it by time object and use some stable tools to translating
for example: we have a dateTime object in c#,and we response it to client,
this is its format,the most standard format :
CreateTime: "/Date(-62135596800000)/"
and it will be translated as a Date object in js . with this , you don't need care UTC or local ,yyyy-MM-dd or yyyy/MM/dd . with some date lib , you can do anything to it as you want in a standard base line . after your all strange operation ,it is still a date object ,still a standard format,and transport it to service side ,it will be a DateTime object(still a standard format) in C# .
if you need get date from some other source like user input,
No matter what you want to do next,first and first translate it to a date object.

SQL Server Date (not Datetime) to JavaScript Date - one day off

I've tried tons of things to fix this, but the problem continues to vex.
I have a Date field in SQL Server (not Datetime, because time doesn't matter), and a Java API (Spring actually) serves this field to my Ember front-end, where a user can edit the field (using an ember-pikaday input, but that may be immaterial).
The problem is that when I switch to edit mode, the date shows one date before, and if I save, that one date before is what gets saved. If I look at what the API is returning, it looks like the following:
"2015-02-03T05:00:00.000+0000"
I'm still very much learning JavaScript (and Ember), so it looks like there's some local time zone information being used automatically (I'm in EST, which is GMT-5) and that's why it's returning the 5AM time.
I really don't want it to do anything at all with time, but as JavaScript date objects by definition include time info, I'm not sure how to get rid of it. I've tried setting the time to noon so that even with a five-hour difference, it will be the same day, but since the database doesn't save the time, the next time I refresh the page, I'm back to square one.
I've run out of things to Google, which is why I posted here. I'm sure I'm missing something obvious and easy.
EDIT: I tried creating a new variable to get just the date part and using that throughout, but when I go into Edit mode, where my Pikaday input comes into play, it still shows the date before, so I'm suspecting that's the cause of the issue, but I haven't seen hardly anyone else complaining of this.
Here is a similar ember.js question:
Ember.js dates a day early
Also make sure your javascript ISO-8601 date has the timezone. I had a similar issue with web api where the ISO-8601 dates were not sending any timezone info and no Z for UTC and the receiver assumed they were not converted to UTC and made them a day earlier '2012-07-27T18:51:45.53403Z // UTC'. You could use Fiddler or Chrome dev tools to see the format of date you are sending to the server make sure the Z or offset '2012-07-27T11:51:45.53403-07:00 // Local' is there.

How to properly compare UTC dates against Local date in LINQ to Enitites?

I am having trouble getting data on a specified date using LINQ.
My dates are stored as UTC in the SQL database (DateTime.UtcNow).
I want to get all records for a date I or a user specifies on the browser (from a datepicker).
I am based in Australia and my database and site is hosted in another timezone and having trouble getting the results correctly.
I have tried using timezoneOffset from JavaScript and passing it to my controller to try converting UTC with the below code but still gives me incorrect results:
myRepo.Where(x => x.Date.AddMinutes(-(timezoneOffset)).Date == date.Date)
I've been scratching my head for almost 2 days already and haven't found a clear and proper solution online.
Help! :)

Fetching Date of Type DateTime with BreezeJS

I'm currently developing an SPA webapplication with BreezeJS. This is all working fine, but I have this question. In my entity I have a table which has a type DateTime, to store the creationdate created with the Entity Framework. This all goes fine but when I fetch the data from the server via Breeze (Server-> to -> client) I get this back in my javascript: Wed May 8 16:23:32 UTC+0200 2013
But via Fiddler2 I see it comes in likes this in my JSON: Created=2013-05-08T16:23:32.038+02:00
Why does BreezeJS add the day name to it? Anyone now where I can get the raw value so I can format the date?
Thanks in advance!
Breeze does not manipulate the day in any way EXCEPT to add a UTZ timezone specifier to any dates returned from the server that do not already have one. This is only done because different browsers interpret dates without a timezone specifier differently and we want consistency between browsers.

Time Zone Sensitive Date and Time Display in Web Applications?

I am looking for recommendations on displaying times in a web application in a time zone other than the user's current time zone.
We store our dates/times in UTC/GMT in the database, so it is not an issue to format the time for UTC/GMT or the user's current time zone. However, in other situations we need to display the time from the point of view of an arbitrary time zone (i.e. every date/time on this page is in Eastern, regardless of whether or not the user is in West Coast, Central, Eastern, etc.).
In the past we have stored offsets or time zone info, then done the calculations in server code in .Net or else we have done some client-side manipulations in javascript that I would prefer to avoid, since it all becomes very dependent on javascript and the user's browser. I'd like to know the best way to do this in a more client-side/MVC type application.
Here is an example:
Date stored in db: 1302790667 (Thu, 14 Apr 2011 14:17:47 GMT)
Converted date displayed for a client in Central time zone: Thu Apr 14 09:17:47 2011
Date I actually want to display, always in Eastern time zone: Thu Apr 14 10:17:47 2011
In the above example, it's easy to get the time in UTC (#1) or the user's current time zone (#2) but it is more difficult to get #3. My options seem to be:
Store offsets or time zones in the db and do calculations on the client - this is what we've done in the past with .Net but it seems even messier in client side code is the path we are currently trying to avoid.
Do the conversion on the server and send down a full date for display to the client - client receives a string ("Thu Apr 14 10:17:47 2011"). This works but it's not very flexible.
Do the conversion on the server, break it into parts and send those down to the client, then put them back together. ("{DayOfWeek:Thu, Month:Apr, Day:14, Hour:10, Minute:17}"). This gives us the correct data and gives us more flexibility in formatting the date but it feels a little wrong for this scenario.
Any other options ideas? How do others handle similar situations? Thanks.
Our results:
I tried out a few libraries like Datejs, MS Ajax, etc. and I was never very happy with them. Datejs didn't work at all in a few of my test cases, is not actively maintained, and seemed to focus a lot on syntactic sugar that we don't need (date.today().first().thursday(), etc.)
We do use jQuery for some basic date/time parsing.
I came across a lot of "roll-your-own" client-side date conversion "hacks", most of which only addressed the conversion to UTC, started off working fine, and then eventually fell apart on some edge case. This one was the 90% solution for a lot of standard UTC conversion but didn't solve our "arbitrary timezone" issue.
Between the code complexity the conversion routines added and the bugs they seemed to cause, we decided to avoid client side date processing most of the time. We do the date conversions on the server with our existing date handling routines and pass the formatted dates or info down as properties to be used by the view. If we need a separate date, we just add another property. There are usually only a few properties that we need at a time (i.e. EventDateUTC, EventDateLocal, EventDateAlwaysAustralia, and EventDayOfWeek).
I offer the suggestion that you look into the Datejs library. It offers a bunch of extensions to basic JavaScript date manipulation, including a "setTimezone()" method and flexible ways to convert a date into a formatted string for display.
I usually hesitate to suggest libraries when their use is not explicitly allowed for in questions, but Datejs isn't very large and it's pretty solid (even though it's called an "alpha" release). If you'd prefer not to rely on something like that, you might want to look at it anyway just to see the basics of how its extensions were implemented.

Categories

Resources