Transferring javascript variables from client to server - javascript

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.

Related

Using Python to parse date/time strings in *exactly* the same way as Javascript?

I have some client-side JavaScript code which reads a string and tries to parse it into a Date() object via new Date(theString), displaying the resulting Date as a UTC string to the user. If it's a string that can't be turned into a Date, of course, it becomes an Invalid Date, in which case instead it displays "Not a date/time."
I also have some server-side Python code which essentially does the same thing: takes the user-submitted maybe-a-date, and stores it as either a UTC string or as "not a date".
The trick is, I need the two pieces of code to always behave exactly the same on every single string. I could certainly just make a tiny Python endpoint that uses the existing Python code to send the appropriate response back to the client instead of using Date() client-side, but for various reasons that's an undesirable solution.
So is there a way to translate strings into dates in Python that's guaranteed to work exactly the same way as new Date(myString) does in JavaScript?
So is there a way to translate strings into dates in Python that's guaranteed to work exactly the same way as new Date(myString) does in JavaScript?
No.
It's impossible, because:
Parsing of strings other than the two formats specified in ECMA-262 is implementation dependent and it is easily demonstrated that different implemetations parse the same string differently (e.g. Why does Date.parse('COVINGTONOFFICE-2') return a real date?)
How various implementations parse unsupported formats is not documented, so you can only determine the rules through observing behaviour of every possible string, including those that look nothing like a date, in every implementation, then knowing which implementation you were trying to imitate

In what format should I store dates where I just need the "YYYY-MM-DD" part [duplicate]

In MongoDB, I only need to make date range queries. But the data set is huge (9 M) and coverting a string to DateTime object (I use Perl script) and then inserting them into MongoDB is very time consuming. If I just store the dates as strings "YYYY-MM-DD", would not the range query gt:"2013-06-01" and lt:"2013-08-31" still give me the same results as if they were of datetime type? Are they the same in this scenario? If so, what would be the advantage of storing as a DateTime object.
Thanks.
If you don't care about time-zone support in your application, then using strings for basic queries in MongoDB should work fine (but if it does matter, you'll want a real Date type).
However, if you later want to do date math or use the Aggregation Framework with your date field, it's necessary that the field is actually a Date type:
http://docs.mongodb.org/manual/reference/aggregation/#date-operators
For example, you could use the $dayOfWeek function on the Date typed field.
You could likely do some simple things like group on year by using $substr (doc) in MongoDB, but the resulting code will not be as clear (nor likely perform as well).
While it's not a huge difference, I'd recommend storing them as Date types if possible generally.
I see in the docs for the Perl driver that developers are warned against using the DateTime due to the fact that it is very slow, so maybe if you use Perl regularly, and the Aggregation Framework isn't a big issue, you'd be better off storing them as either numbers or as strings, and converting them as needed in Perl.
If space is an issue, remove unnecessary characters (such as the -):
20130613 ->
4 bytes for length of string
8 bytes encoded as UTF-8
NULL character
That would be 13 characters. A DateTime value in BSON/MongoDB requires 8 bytes on the other hand (as would the Perl $time function).
(I'd strongly recommend you do a bit of performance testing to find out if the performance impact of using a Date type in MongoDB with Perl will impact your typical workflows.)
The advantage of DateTime is a few bytes less on disk. bson stores DateTime as an integer, but "2013-08-31" is a string, at 20 bytes right there.
ISO-8601 (http://www.w3.org/QA/Tips/iso-date) is meant for being able to sort quickly.
In this case, I would always store as datetime.
edit: How time-consuming are you seeing this string-to-datetime conversion? Are you sure that is your bottleneck? I have a hard time believing the conversion is taking as long as you claim.

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.

Caveats against using timestamp values for dates in Javascript

I have been using 'date as a long' (getTime() / +) all the time when operating on dates in client side Javascript, for comparison, evaluation and also for transport of date from (not to) our Java server side to client side Javascript.
It saved me from the headache of browser misbehaviour in date handling.
But recently this practice was questioned and I still haven't got any reason why I should use string dates instead. Are there any problems in this usage of timestamps that I am unable to see?
There should not be any problem when your server side is Java.
Only thing I can add is - it is handy to use a javascript library like moment.js on client side. moment.js is a rich date handling library. Go for it if you have to do lot of date manipulations, display in different formats or read date from user.
JS timestamps are milliseconds-since-the-epoch. Most server systems (unless you're dealing with node.js) use plain seconds-since-the-epoch. Any JS timestamp representing "now"-type dates are therefore WAY past the size limits of a normal 32bit signed unix timestamp, and will be truncated/corrupted.
Sending a string avoids this, because pretty much any decent system can accept a date string and convert it back into its own native time system, whereas taking a corrupted truncated int is just a matter of garbage-in, garbage-out.
Of course, if your server-side systems are aware they'll be receiving a JS timestamp, they can accept as a string, then do some basic truncation to lop off the milliseconds component, leaving them with a normal seconds-based timetamp string that can be converted to an int.

Asp-net web api output datetime with the letter T

the data in the DB look like this
2011-09-07 14:43:22.520
But my Web API outputs the data and replace the space with the letter T
2011-09-07T14:43:22.520
I can replace the letter T with a space again in jquery, but can I fix this problem from the Web API (make the web api output the original data?)
I also do not want the miliseconds at the end. How can I get rid of them?
The format of how you see the date in the database is usually irrelevant, because it should be passed into .Net as a DateTime - not as a string. (If you are storing it as a varchar in the database, you have a bigger problem.)
ASP.Net WebAPI is returning the value in format defined by ISO8601 and RFC3339. This is a good thing, as it is a recognized machine-readable format. You probably don't want to change it.
If you really want to change it, you would need to implement a custom JSON.Net JsonConverter, deriving from DateTimeConverterBase. This is discussed here and here.
But instead, you should consider how you are using the actual result in your client application. You mentioned jQuery, so I will assume your consumer is JavaScript. In many browsers, the ISO8601 value that you have is already recognized by the JavaScript Date constructor, so you might be able to just do this:
var dt = new Date("2011-09-07T14:43:22.520");
But this won't work in all browsers. And Date doesn't have a whole lot of flexibility when it comes to formatting. So instead, you might want to consider a library such as moment.js. With that in place, you can do this:
var m = moment("2011-09-07T14:43:22.520");
var s = m.format("YYYY-MM-DD HH:mm:ss"); // output: "2011-09-07 14:43:22"
Please note that the format string here conforms to moment.js, not to .NET. There are differences in case sensitivity. Please refer to the moment.js documentation for details.
One other thing - since the value you provided doesn't have either a Z at the end, nor does it have an offset such as -07:00, then I assume it came from a DateTime whos .Kind value is DateTimeKind.Unspecified. You should be aware that when this gets sent into JavaScript (or anywhere else for that matter), there is no information about what time zone is represented. JavaScript will assume the local time zone of the browser.
If that's not what you had intended, then you need to store UTC values in your database, and make sure they have DateTimeKind.Utc so they get serialized with a Z at the end. JavaScript will normalize this to the browser's time zone, but you will still be talking about the same moment in time.
Alternatively, you could use a DateTimeOffset type - which would serialize with the specific offset. JavaScript will still normalize this to the user's time zone.

Categories

Resources