Convert UTC to localtime best approach? - javascript

Am using:
mongoDB to fetch data to the server which is based on: node.js and express. Template engine is PUG aka. Jade.
in each document stored inside the DB there is a date attribute stored as UTC.
Question/problem.
I need to convert UTC to the clients local-time.
Solving alternatives:
Using Aggregation in MongoDB
Using moment.js library and make the conversion in node
Pass moment.js object inside the view and make the conversion their,
as suggested in this post:
How can I format a date coming from MongoDB?

Using moment.js to format an ISO 8601 date string to local time can be achieved like this:
let moment = require('moment');
let localizedDate = moment('2014-06-01T12:00:00Z').format('LT');
console.log(localizedDate);

Related

How to solve problem of timezone in Node js and mongodb?

I'm trying to insert start and end time like entry and exit time logic into Mongodb from node js.
My local system's timezone is IST. +5:30 offset for both client and sever.
So now follow this example.
entryDate: 15-10-2018,
start: 15-10-2018 01:00:00,
end: 15-10-2018 05:00:00
Now since i'm on same timezone on client and server, it won't change my date value and create new object.
Then i'm storing this data into MongoDB. As you know that mongo db will convert date to UTC and then stores it. So in my DB it will look like this.
entryDate: ISODate("2018-10-15T00:00:00Z"),
start: ISODate("2018-10-14T19:30:26Z"),
end: ISODate("2018-10-14T23:30:26Z")
So now if I want to search a query that should give me records for dates and time between 15 to 16 let's say then i won't get any data.
Now consider this case. I moved app on to the server. Now servers timezone is in UTC. So every date I pass will be converted directly in UTC so it'll insert same data like before.
Now difference here is when i want to search date range in IST timezone then it will give me the exact date to search like (15-10-2018 00:00:00) to (16-10-2018 00:00:00).
Where on server it will convert this date to UTC and can give me one day less or may be higer time like (14-10-2018 18:30:00) to (15-10-2018 18:30:00). So from the start my query is wrong.
So how to solve this issue? Thank you.
After doing some research. I have a solution.
Get your date on the client side.
Convert that date to UTC date and pass date string to the server. Like 01-01-2018 10:00:00. (Note: we are just converting date, not the timezone)
On the server side create a date object from the provided date that will convert the date to UTC by default with that same time.
Store the date on the server side with MongoDB. Since the date is in UTC it won't convert the date again and store it as it is.
Now from the server, you will get the date in UTC format which will be like '2018-01-01 10:00:00'.
Now on the client side, create a date object from this date. This will convert your date to actual date that you passed.
This solved my problem.

Generate WCF JSON format Date with moment.js or another javascript library

I am consuming a WCF Service in Javascript and need to play around with dates.
I was looking around for some nice DateTime handlers for the format the DataContractJsonSerializer generates { "date": "/Date(1260597600000-0600)/" } and found moment.js. moment.js is really excellent to consume this date format, handles the format including the timezone.
What I need now is generate the WCF date format from a Javascript or moment Date to send dates with timezones in the request on my POST method and looking in the documentation of moment.js couldn't find anything that has the output I need.
Any idea how to achieve this with moment.js or any other js library?
Thanks.
With moment.js:
yourMomentObject.format("/[Date](xZZ)/")
Example:
Without moment, you can write your own function that takes uses the Date object's .getTime() function, and .getTimezoneOffset() functions. However, the offset has to be negated, then formatted properly before being added to the string.

Parsing Apache Log Timestamps with JavaScript

I'm attempting to use moment.js to format Apache log timestamps (14/Jun/2015:11:05:54 -0700) as proper MySQL DATETIME format.
Getting the MySQL DATETIME format is a breeze. But moment seems to only auto-detect ISO 8601 formats. My Node.js console output when passing in the Apache log's timestamp into moment:
> moment( '08/Jun/2015:15:03:29' ).format("YYYY-MM-DD HH:mm:ss")
'Invalid date'
I can't figure out a way to parse the Apache log timestamp without doing a ton of string splitting in JavaScript. Is there a clean way of loading the Apache log timestamp into moment? Or perhaps into the Date object?
NOTE: Changing the Apache log's timestamp format wouldn't work for my case, because I'm working with old log files, not new ones.
You need to tell moment what format the string is in so it can parse it.
Something like:
moment( '08/Jun/2015:15:03:29', 'DD/MMM/YYYY:HH:mm:ss Z').format("YYYY-MM-DD HH:mm:ss")

Ajax post javascript date as UTC OR server Time

I am trying to post a created date to an ASP.Net MVC controller without the date being modified by the serializer. I am looking for some kind of way to do this on the client.
The date is being constructed as follows:
var priceDate = new Date(name.split("-")[1], name.split("-")[0]-1, 1);
The date is valid and the problem is the serializer is adding the timezone offset which i don't want. The javascript date should be UTC but this doesn't seem possible.
This problem is expressed in different ways all over the place with all kinds of solutions that just seem way over the top. Is is possible to make a javascript date UTC or devoid of timezone information from the client?
There is toISOString() function which returns dates in standardized format and always does zero time zone.
Server accepts dates in local zone, so you need to do next date.ToUniversalTime().
So javascrript date.toISOString() equals to c# date.ToUniversalTime().

Date format in mongodb/mongoose

When I create a date in javascript it is in zulu, when I save it in my mongodb via mongoose it is transformed to UTC (its keeps the same time value, but the timezone is changed). I'd like it to stay in zulu when saved, how can I set this option in mongoose ?
thanks
MongoDB stores all DateTimes in UTC. Any local times you supply are converted to UTC when stored in the database. The recommended approach is to always convert DateTime values to UTC yourself before storing them in the database, that way you are in full control.
Resources:
https://jira.mongodb.org/browse/CSHARP-185
Dealing with how MongoDB stores DateTime when used with Service Locator Pattern

Categories