Date being automatically converted in browser window - javascript

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.

Related

How to save correct time in database?

I have one object called appointment which has two properties: StartDate and EndDate.
When I make POST request I send these values using ISOString time .
this.appointment.StartDate.toISOString()
On the server-side, I received these properties with correct values. Also, it seems to be correct when I create model in order to save appointment to the database. I used .ToUniversalTime() method.
var newAppointment = new Appointment()
{
StartDate =Convert.ToDateTime(model.StartDate).ToUniversalTime(),
EndDate = Convert.ToDateTime(model.EndDate).ToUniversalTime(),
SpecialityId = speciality.Id,
LocationId = location.Id,
PatientId = patient.Id,
UserId = user.Id,
Observations = model.Observations
};
But in database I found another values. Can explain somebody why is this behaviour ?
For instance, I used 2017.09.01 11:00 for StartDate and in database i found 2017-09-01 08:00
The server and database is located in the westeurope.
A few things:
Don't call ToUniversalTime in a web application. It's designed to convert from the server's local time zone to UTC. The server's time zone should be irrelavent to your application. Web applications should never use ToUniversalTime, ToLocalTime, DateTime.Now, TimeZoneInfo.Local, DateTimeKind.Local or any other method that uses the time zone of the computer it's running on.
Ideally, on the server side, your model.StartDate and model.EndDate would already be DateTime objects, because they'd have been deserialized that way. Therefore, you probably don't need to call Convert.ToDateTime. If they are strings, then I would adjust your model class accordingly.
On the client side, assuming StartDate and EndDate are JavaScript Date objects, and they were created using local time values (that is, the time zone of the browser), when you call toISOString, you're not just getting a string in ISO 8601 format - it is also converting it from the browser's time zone to UTC.
In your example, the UTC time is 3 hours ahead of UTC for the date and time shown. From your profile, I see you are located in Romania, which is indeed UTC+3 for this date, because it is currently observing Eastern European Summer Time. When Summer Time ends (on October 29, 2017 at 04:00), it will return to UTC+2. For this reason, you cannot simply add three hours to all values.
If you want to send local time values from the client, you should send them in ISO 8601 format, without any Z or offset, for example 2017-09-01T11:00. There are several ways to achieve this:
The best way is to not have them in a Date object to begin with. For example, if your input uses the <input type="datetime-local" /> input type (as specified in HTML5), the .value property is not a Date object, but rather a string in ISO 8601 format.
If you can't avoid a Date object, then create a local ISO string, like this:
function dateToLocalISOString(date) {
var offset = date.getTimezoneOffset();
var shifted = new Date(date - offset * 60 * 1000);
return shifted.toISOString().slice(0, -1);
}
OR, using Moment.js:
moment(yourDateObject).format("YYYY-MM-DD[T]HH:mm:ss.SSS")
Lastly, you will probably read advice from others about storing these as UTC. Don't listen. The advice "always use UTC" is shortsighted. Many scenarios require local time. Scheduling appointments is a primary use case for local time. However, if you need to act on that appointment, you'll use the current UTC time, and you'll also need some information about the time zone for the appointment so you can convert from UTC to the appointment's time zone. For example, if this is something like an in-person doctor's office appointment, then it's safe to assume the time zone of the doctor's office. But if it's an appointment for an online meeting, then you'll have to capture the user's time zone separately and apply it on the back end where appropriate.
The problem is with your current timezone.
What your application does is get current timezone (+3) in this case.
Now it got your timezone but it will convert to utc time. So what will happen, your current time will be -3 hours.
If you not adjust to summer and winter time then you can simply add 3 hours to the datetime. Otherwise you have to get the offset of your timezone and add that to the current datetime value.
Take care if you use this application in different timezones. For example You life in +3 and some else life in +2 timezone.

Convert UTC string date to valid mongo date in JavaScript

I have this TimeStamp = "2017-08-02T08:00:38.977" which is provided to me from 3rd party API feed. It is already in UTC.
I need to log this into mongo and I want it to be a valid Date type in mongo for querying but I'm struggling to convert the damn thing correctly so it's stored 'as is'.
e.g.
TimeStamp = new Date(TimeStamp) gives me Wed Aug 02 2017 08:00:38 GMT+0800 which when I insert to mongo appears as 2017-08-02 00:00:38.280Z i.e. "TimeStamp" : ISODate("2017-08-02T00:00:38.280Z")
I tried toISOString and various other things but they all change the time in bizarre ways and appear in mongo completely different to what i expect.
Can someone please tell me how to just insert the string variable 2017-08-02T07:55:47.977 into mongo so it remains exactly the same but is Date type.
Regards
fLo
Update
Incoming string timestamp from API = 2017-08-02T08:30:41.39
new Date(TimeStamp) = 2017-08-02T00:30:41.390Z
Document in Mongo after insert = "TimeStamp" : ISODate("2017-08-02T00:30:41.390Z")

Date entry feed is wrong even when both Server/Client are in same timezone

Pre-conditions:
Both my server and client machines have same timezone,i.e. India Standard Time (UTC +5:30).
I am using Meteor JS 1.5 + MongoDB 3.2 on CentOS 6.9
I have set the linux server /etc/localtime/ to Asia/Kolkata and when I gave command date, it showed me below,
Wed Jul 12 13:40:25 IST 2017
Actions:
Below is the peice of code that runs on server methods,
History.insert({
"time": new Date(),
});
Since the code ran at 13:40PM IST, the date entry show in mongoDb is as below,
> db.History.find({}).pretty();
{
"_id" : "zFHFgBfGL2JxNR95N",
"time" : ISODate("2017-07-12T08:10:10.175Z"),
"result" : 1
}
Question:
Why the date entry made using Meteor JS is not the same as of set timezone? and why not the same as the machine (which is appx 13:40PM)?
First, IST is UTC +5:30, so 13:40 IST is the same time as 08:10 UTC.
Now checking the MongoDB docs on the date type:
Internally, Date objects are stored as a 64 bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970)
Note that the timezone is not being stored at all.
Further down in the same doc:
The mongo shell wraps objects of Date type with the ISODate helper; however, the objects remain of type Date.
This is why you are seeing ISODate("2017-07-12T08:10:10.175Z") being returned when you query in the Mongo Shell
If you switch to the Meteor Shell and query your data, it will be shown as a javascript Date type again, and in the timezone defined on your server.
// try this in Meteor Shell
History.find({}).fetch()
And again if you send this date to the client, there it would be displayed with the timezone defined on their device.

FullCalendar adjusts timezone when set to local but not on Europe/Athens

Hi i m using FullCalendar 2.1.1 and i face an issue with timezone.
The application is being developed with Yii framework and when i set the timezone to Europe/Athens
'timezone' => 'Europe/Athens'
timezone is set to GMT 0000 it neglects the setting while if i set
'timezone' => 'local'
timezone is set to GMT 0200 as expected.
The problem is that the dates that are used in the appare based on Europe/Athens zone, so i don't think it is safe to rely on local time.
Actually your machine is not aware of 'Europe/Athens' time zone so you have to define it.
How to do this ?
refer to here :
http://fullcalendar.io/docs/timezone/timezone/
Timezone string (like "America/Chicago")
Use this mode if you store timezone information for your events and
you want them displayed in a timezone that can be customized.
{ title: "event1", start: "2013-10-20T02:00:00+09:00" }
// ^ ^
// will display as 2:00 |
// |
// timezone offset will always be +09:00
If you want to fetch TZ settings , usually it is done in server side , but using node.js + moment.js will be easier to for you , please check this :
http://momentjs.com/timezone/docs/#/using-timezones/

Microsoft AJAX serialized dates with time swift

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;

Categories