DateTime.Min JSON Serialisation Incorrect - javascript

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.

Related

UTC offset from server to client

In our application we are Saving the UTC DateTime in DataBase. Client (javascript) is sending the datetime in Local TimeZone and at controller level we are converting it to UTC time before saving the date in Database.
Both the client and servers are on different timezones.
we are fetching date from database in UTC Using Entity Framework with
DateTime.SpecifyKind(_CreatedDate, DateTimeKind.Utc);
So should we again convert the DateTime to local DateTime at controller or should we handle all the DateTime conversion logic at the client.
When sending DateTime instances to the server conversion conversion to UTC should happen as early as possible. In this case by the client and as your client is javascript you can use the method toUTCString. If you are using momentjs you can use utc.
When receiving DateTime instances from the server conversion conversion to local time should happen as late as possible. Make sure that persisted dates/retrieved dates are in UTC when you create them. Again, it is the client that should be converting them to local date time instance.
Finally send all datetime instances between client and server using ISO8601 format. Momentjs, javascript's date object, json.net all can do this. This ensures nothing is lost and no cultural specific bugs are introduced.
As to why it should be handled at the client is very simple, its easiest to do it there. Only the client truly knows its timezone, this is usually very difficult to "guess accurately" on the server side. The only reason not to do this is if you wanted to store a users timezone info with their profile but even this can get very tricky (what happens if the user travels or if they move location, etc).
As to how to persist you can use either a DateTime type or a DateTime with offset type (the true type names depend on the RDBMs you are using). Which one you choose should depend on if it is important to know the offset from utc at the moment it was saved. So far I have not had a need to do this but maybe it is important for you. It has no influence on the actual point in time as a DateTime should represent the UTC point in time and with offset should represent the local time with offset to get back to the UTC point in time.
Here's the way we do it in our projects. In my opinion, you should be using datetimeoffset in your database. This allows you to be able to identify what timezone the date was saved in. Then, when you send your date from your client to your server, just make sure it's sent in datetimeoffset.
When you send the datetimeoffset from the server to the client, you can do the conversion on the client side. I don't think anybody would argue that MomentJS Timezone is the best library for this. Look over it and give it a shot.
http://momentjs.com/timezone/
Elaborating on DateTimeOffset
DateTimeOffset is another datatype like datetime except datetimeoffset adds an hour offset to determine the timezone. For instance, let's say you're in Central Timezone and you want to save the time 08:00 am. Well, in Datetimeoffset, it would be something like 08:00:00:00 -04:00 declaring that the offset was -4 (central timezone). This makes it easy because you don't have to do any math in your head when reading it and you really don't have to do any conversions (let MomentJS do it for you). When you read it, you will always know that "Oh, it was 08:00 am for whomever saved the time, and it looks like they saved it in Central timezone."
Since it's quite relative when is the "Proper" time to convert.
The only absolute rule i think is valid is this one.
UTC time is the only Real meaningful data
Any other conversion to any timezone is just a "Display" for me
So follow the same rules as you would with the rest of your data.
Like converting a Boolean to a Checkbox on the view.Or sending that checkbox value as Boolean to the server.
And that's the soonest it Reaches or Leaves the UI.

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.

How do I convert a new Date() into the client's time?

I'm trying to get
date = new Date()
and then make it into a local time from the client, how would I go about doing that?
I would need the Date, in this format
Day[Mon,Tues, etc.], Day of the month[18], Month[Nov,etc.], Year, then the time in either a 24 hour format or a 12 hour format, seconds would be good.
I've tried using the getTimezoneOffset(), but I'm not sure how to use it.
Dates in JavaScript should always be in the format of the client computer.
If toLocaleDateString isn't working for you, I recommend Moment.js
Using toLocaleDateString:
console.log(new Date().toLocaleDateString());
Using Moment.js:
console.log(moment().format('llll'));
By a "local time from the client" I assume that your server returns some time from, let's say, GMT-0 , and your client is at GMT-3.
Knowing your server timezone, you could do some trick to do the math using jsTimezoneDetect (http://pellepim.bitbucket.org/jstz/).
And regarding the statement "Dates in JavaScript should always be in the format of the client computer.", that's assuming you are using Javascript on the client side, while in fact, you could be using it on the server (nodes).
BTW, when you say "I'm trying to get date = new Date()" I'm assuming you're doing that on the server with nodejs, otherwise, both jasonscript and Loper324 are right, you are already in the client so that Date will be in the timezone of the client. Or were you referring just to the formatting?

json date returned from wcf service not consistent

I have a service that returns a date. The weird thing is that most of the time it comes back like this: /Date(1364227320000)/
but sometimes it returns the date like this /Date(1364050020139-0400)/
when I open up the visual studio debugger, the dates look the same for each one (minus differences in time)
What could account for this difference?
This is handled in System.Runtime.Serialization.Json.JsonWriterDelegator.WriteDateTimeInDefaultFormat(). If the DateTimeKind is Unspecified or Local, it adds the UtcOffset to the end (the -400 part, meaning Utc - 4 hours).
It depends on the kind of the DateTime object (i.e., the value of its Kind property). If you're returning a DateTime with DateTimeKind.Utc, there will be no offset. If the date time is of kind Local or Unspecified, the offset will be written out.
You can find more information about the format in the "DateTime Wire Format" section of the "Stand-Alone JSON Serialization" page on MSDN.

Date format on client browser

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"

Categories

Resources