Universal DateTime Format - javascript

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.

Related

Weird format Date to `toLocaleString` in 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.

how to subtract php date from Javascript date

I create project with php Laravel framework and VueJS and I want to get the difference between server time and client time to process some data time out by Javascript in the client browser.
How can i do that?
I need to change the format of one of the dates to be available to manage by other language functions and property.
how to sub (minus) Carbon::now() got from php api Date.Now() in JS.
I do that to get the difference between client clock and the server.
In order to "speak" in dates, the best practice is to work with timestamps.
The server can have its own timezone offset which is why it is best that it will expose any managed dates in UTC.
The client, on the other hand, will need to convert the UTC timestamp to its locale date, which can be done by adding its timezone offset.
Having said that - you will probably want to calculate the data timeout on the server, since the client can be bypassed, thus exposing a timed-out data to potential hackers.
Hope this helps :)

sending javascript date object to server without adjusting for time zone difference

Is there a way to send data from the client to a server without adjusting the time to account for the time zone difference between the client and server?
I have an angular app with a nodejs server. When I send a date from a form to the server via an HTTP request and log the date on the server, the date changes to the time in the time zone of the server.
I'd like to send the date object back and forth without it changing.
I always use http://momentjs.com/ when dealing with javascript dates. When a date object is created the systems timezone is used, so you'll always have to adjust for the offset. The easiest solution is to do one of the following
use a string and parse it
use moment().format() with a custom format
use UTC on the client and server
use ticks or unix epoch
There really isn't a great solution, you just need to be consistent.
Use milliseconds .
let now = new Date();
let time = now.getTime();
time contains number of milliseconds in UTC timezone always. In the server you can convert milliseconds to date . This way you dont need to worry about timezones.
According to MDN Javascript Date objects are constructed using UTC.
You can send the date object back and forth without ever changing it, it will simply be interpreted relative to the 'locale' of wherever it is being used.
If you'd like to maintain the local date and time irrespective of location (between different client and server locations) you'll probably need to pass along the locale of the Date as well as the Date itself.
A way to do this is to format your Date as a string in ISO 8601 format with a time offset (like +0100.)
That way you'll get both the local time and the offset used for every time.
You can construct it by hand using the Date.prototoype.toISOString method but that will still be relative to UTC.
Here's another Stack Overflow question on how to get the correct offset yourself.

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.

Transferring javascript variables from client to server

I am programming a strange script that consists of transferring variables from client to a nodejs server.So if a have a date variable, how can I transfer it and use the same variable on the server?Is there any way to serialize objects and retrieve them on server side in a way that they remain the same type (date, function, variable, string, object...)?
Thank you
You can serialize a date by converting it to a number which can be sent via JSON.
new Date(+new Date)
is perfectly valid.
The prefix + in
+new Date
converts the newly created date to a number, and
new Date(myNumber)
reconstitutes a date from a number.
You might check out DNode in addition to nowjs. I've been watching both of those projects but not dabbled in them yet. However, I get the sense that DNode it is building more traction in the node.js community and I hear praise for it all the time.
https://github.com/substack/dnode
http://substack.net/posts/85e1bd/DNode-Asynchronous-Remote-Method-Invocation-for-Node-js-and-the-Browser
Timezones are very important in my application, so I've found that serializing dates to ISO8601 formatted strings for dates works best. #Mike's solution is great if you don't care about timezones, or can assume that all dates are UTC. There are plenty of javascript libraries to help serialize/deserialize ISO8601.
Now.js could abstract all of the serialisation, deserialisation.. it provides a shared namespace between node.js server and browser client:
http://nowjs.com/
As was posted before me, serialize the Date Object to a string literal, either the value in miliseconds or the formatted Date String.
Use a POST request passing the Date string in the request body or a GET requests passing the string via query parameter to get it to the server. There you may deserialize the string using the Date constructor.

Categories

Resources