I have an MVC 3 web application for a web API, a controller emit json.
In the json result I see dates are being serialised automatically
as
{
Flag: "U"
EventId: "168ef1d4-60ca-4fa1-b03b-8c3207650347"
EventTitle: "test event 11"
DateTimeStart: "/Date(1369217469310)/"
IsCustomEvent: true
Location: null
}
in javascript I need to convert DateTimeStart in human readable format and using this code
var date = new Date(1369217469310);
alert(date);
I see the resulting data as
Wed May 22 2013 12:11:09 GMT+0200 (CEST)
This is 1 hour a head of the date stored in the application wich is 22/05/2013 11:11:09.
I would like to know where the issue could be and how to fix it:
Is it .Net serialising dates by default using CEST wich is +1 UCT, in this case how to set up UCT at 0?
Is it an issue when converting in the date using JavaScript?
Please let em know how you would fix it, thanks!
I haven't enough information to advice about the server side. Generally the source of the problem on server side may be the CultureInfo set in you application. You may consider to convert all datetimes as UTC before sending it to the browser. Check the DateTime.ToUniversalTime() method.
On client side you also are able to fix the offset between regional time and UTC. There is no build in function to do this, but it's very simple operation to perform. Check the code below.
var date = new Date();
var dateWithOffset = date.getTime() + date.getTimezoneOffset() * 60000;
Related
I currently am experiencing a problem when printing a date on the frontend of a website I'm working on. The date is retrieved via Node.js (mysql module) from a a MySql db, where it's stored in a MySql DATETIME format. The view engine being used is Handlebars.
The problem consists in the date being automatically converted when in the browser window, and I'm currently out of luck with trying to figure out where and how this is happening. Console.logging the 'date' field retrieved from the node db query gives me a 2018-12-27T18:00:00.000Z type of date, but in the browser this date is getting printed as Thu Dec 27 2018 19:00:00 GMT+0000 (Coordinated Universal Time). I already tried to do a date = date.toString() conversion on the Node side, but to no avail.
-
This is the code on the node.js side:
app.get( '/blog' , ( req , res ) => {
db.get().query( `SELECT * FROM posts` , ( error , results ) => {
res.render( "./blog.hbs" ,
{
pageTitle : "xx - My Blog" ,
posts : results
} );
} );
} );
Thanks in advance to anyone willing to help me solve this puzzle.
Have a nice day.
The database is using the ISO DateTime format to store the timestamp, which is pretty standard and safe. Putting this timestamp inside the JS Date Constructor should not result in any type of conversions.
However, when the toString() method on the Date object is called, it usually generates the timestamp by taking the local machine's timezone offset into consideration. And the timezone is also added at the end of timestamp.
So from what I can guess, this is probably not an issue on your server side, rather you should check the code of the client application you're running in the browser.
If you want to output the exact same timestamp on the client side as the server side, then use the Date.toISOString() method.
I have Javascript based app (using Nativescript) in which I'm using moment to do some time manipulation. My server returns dtae times to me in the following string format "9/14/2016 4:52:20 PM" Which are Not in UTC. Depending on where the user is I would like to change the time stamp of this string to match their time zone. So I'm trying to get a string that would look like this "4:52 PM" in EST or "12:52 PM" if it's pacific timezone. I'm currently trying to do this using MomentJS like in the following way:
exports.dateTimeStamp = function(value) {
var utcDate = moment.utc(value);
var localDate = moment(utcDate).local();
var formatedDate = moment(localDate).format('LT');
return formatedDate;
};
Unfortunately this isn't working correctly. As of now If I try to do this and the user is in ****EST (GMT-4:00)**** and the string value I pass in is equal to "9/14/2016 4:52:20 PM" I'm getting back "12:52 PM" Rather than "4:52 PM" Could some one point out what I'm doing wrong? My thought is in involves the switch to UTC but that seems like it's necessary from what I have read.
EDIT
I've looked into Moment Timezone, but I don't think that will work since my application is global and it seems Timezone requires a hard coded country/city string to be passed into it. In my case Javascript being used in an Android App. So I get the locale and culture info from the device. Maybe I'm just not quite understanding how to use it.
On ASP.net MVC application where I save the date on datetime field in SQL sever db.It saves like this 2015-04-22 18:43:18.967.So now I need to show it as MST (Mountain Standard Time) on client side.So how can I do that ? I can use Moment.js or any other JavaScript library for that.Thanks in advance.
If you send the timestamp to the client and you are using momentjs, then it's pretty simple
var day = moment(TS_IN_MILLISECONDS).tz('America/Denver')
With the string you provided, you can do this:
var UTCTime = moment.utc('2015-04-22 18:43:18.967').toDate();
var MSTTime = moment(UTCTime).tz('America/Denver').format('YYYY-MM-DD HH:mm:ss');
So this will depend on what local time your server is running in (or if it's just pulling UTC it'll be a bit easier). But you can yank the timezone offset like this: dateTime.getTimezoneOffset(), modify it it to reflect the offset difference between your server's timezone and MST. And then modify your original datetime to reflect the new offset.
This may be a good post for reference.
Also refer to here:
dateTime.setTime( dateTime.getTime() + dateTime.getTimezoneOffset()*[math to adjust your timezone] );
Colleague and I have scabbed together a little app that uses a bunch of JS in the browser, and communicates with a Tornado (Python3) server via JSON, the server uses mongodb as a backing store for persistent data. This is a sort of first for both of us.
What we're finding difficult is how to interchange datetime information between the JS and Python. We do believe that we should use UTC times for everything. JSON doesn't have a datetime literal, so we have to encode it somehow. We naively (?) used the JS notion of milliseconds from 1970 and have been sharing big integers back and forth. So the JS code might get the current utc now time with something like:
var newTime = new Date().getTime();
On the Python3/mongo side, we'd like to use real datetime objects, so we convert that with something like:
datetime.datetime.utcfromtimestamp(jsMilliseconds / 1000)
But then when we have to send date back, said Python3 object only has a timestamp() method. And round tripping that doesn't seem to create the same time. So we've been frustrated with this.
What we're looking for is for someone with experience to give us a good set of idioms to use here. Should we be using strings, instead of the ms integers when passing back and forth with JSON? What are the recommended methods to use on both sides to go between that format? Or should we stick with the integers and which methods should we be using then?
There are obviously a lot of requirements to consider when dealing with time. However, in the case you want to maintain a Date/Time to be displayed to user in their time zone and use mongo/python/java/javascript, I've used ISO 8601 date formats and always store UTC (Zulu) time. Also, if you truly want to maintain the actual time that something occured, not only do you need to store the "date/time" you need to also store the "timezone" (for example IANA timezone string) where the event occurred.
For a lifetime a reading, you can search for "date time best practices". This answer has a good start on discussion: Daylight saving time and time zone best practices
Alright, now to the code (all of this can be found readily on the internet if you search for
" parse||output ISO 8601 parsing" (e.g. "python parse ISO 8601 date string"):
JSON - on the wire between JavaScript and Python backend send a complex (can be simple if you have no need to preserve time zone) object with ISO-8601 formatted string and string to store time zone string:
{
"dateTime": "1970-07-10T12:00:00.047Z",
"timeZone": "America/New_York"
}
Java Script
a. read datetime string JavaScript: Which browsers support parsing of ISO-8601 Date String with Date.parse
var d = Date.parse("2011-04-26T13:16:50Z");
b. write datetime string How do I output an ISO 8601 formatted string in JavaScript?
var date = new Date();
date.toISOString(); //"2011-12-19T15:28:46.493Z"
Python
a. read datetime string How do I translate a ISO 8601 datetime string into a Python datetime object?
import dateutil.parser
yourdate = dateutil.parser.parse(datestring)
b. write datetime string Python - Convert date to ISO 8601
import dateutil.parser as parser
date.isoformat()
Mongo - store datetime as native datetime field http://docs.mongodb.org/manual/reference/mongodb-extended-json/#date
a. store datetime string (notice "$date" and that datetime is in ZULU/UTC (denoted by 'Z')):
"dateTime" : { "$date" : "1970-07-10T13:00:00.047Z"}
Reference:
1. IANA TimeZone Databasehttp://en.wikipedia.org/wiki/Tz_database
2. The google calendar API (event resource) can be used as an example for RFC 3339, as well (see start/end): https://developers.google.com/google-apps/calendar/v3/reference/events
I have a database field called CreatedDate which is a timestamp field and holds the date and time. It currently holds the GMT time.
At the moment this field is displayed as it is on the web pages.
We want to amend this to show date/time as per browser local time zone
Can you please let us know how we can do this.
Thanks in advance
If you can represent the universal time as a count of milliseconds since the 1 Jan 1970 epoch at the server then you can have the page code construct Date instances at the client using the client time zone, but starting from that UTC reference. It's the normal behavior of the Javascript Date() constructor:
var clientDate = new Date(serverUTC);
Now exactly how you get that UTC value depends on your server language. In a JSP page it'd be pretty simple:
var clientDate = new Date(<%= whatever.getTheDate().getTime() %>);
or
var clientDate = new Date(${something.theDate.time});
Once you've got the date value as a client-side Javascript Date instance, you can just update the field(s) with the string. There are no built-in Date formatting tools, but the old standard date.js might help with its ".toString()" formatter.