Convert UTC string date to valid mongo date in JavaScript - 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")

Related

Date being automatically converted in browser window

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.

angular $http.post changing date to UTC date

I was trying to post some data to my REST api which has date.
Now while I debug, my date parameter is a JS Date object with correct date in my timezone: Tue Apr 04 2017 00:00:00 GMT+0530
after it leaves my code, and I see the same in network tab, it is converted to UTC date: "2017-04-03T18:30:00.000Z"
I searched for the solution according to which I need to include locale file of angular in my index.html which I did:
<script type="text/javascript" src="resources/js/angular/angular-locale_en-in.js"></script>
but it doesn't help.
I've seen solutions like adding date format to filter or something, but I want a global solution.
Any help?
Thanks :)
Handling date, time, and timezone have confused me too. May be this answer gives you some insight on how you can handle them.
Try the following code in Chrome's developer console and see how same date is presented in different formats:
var date = new Date();
date.toISOString(); // "2017-04-29T09:54:28.714Z"
date.toGMTString(); //"Sat, 29 Apr 2017 09:54:28 GMT"
date.toLocalString(); //"4/29/2017, 3:24:28 PM"
Any date that you create on client always records the date at zero timezone offset i.e. UTC+/-00:00 Z. For simplicity you may think UTC and GMT as same. When it comes to display purpose the same date is presented as per the browser's timezone. If you do console.log (date) it'll output Sat Apr 29 2017 15:24:28 GMT+0530 (IST) but that doesn't mean that the internal recording of the date is as per browser's timezone. It's just presented on screen/console as per browser's timezone.
Look at date representations not as being converted from one timezone to another but look at them as different representation of the same date. In your browser it is represented as GMT+0530 offset and when it is sent to server it is the same date at zero timezone offset.
As per your comment, if you choose 4th Apr at 00:00 AM in GMT+0530 timezone, internally it'll be 3rd Apr at 18:30 PM in at GMT+0 i.e. zero timezone offset. Let it go to server as it is. When you need to use this date, it comes back from server as 3rd Apr and it'll be displayed in browser as per the browser's timezone offset. There is no conversion involved, it is one date with different representation.
I once asked a related question, may be this adds more clarification.
And overall, this answer is still same as #geminiousgoel and #charlietfl answers.
Scenario :
Send date from UI into API call as an epoch time (UNIX Time) instead of date string. You can use getTime() method to convert the date into epoch time.
var dateStr = "Tue Apr 04 2017 00:00:00 GMT+0530";
var dateEpoch = new Date(dateStr).getTime();
console.log(dateEpoch); // 1491244200000 (Local Time)
At receiver end, they have to convert this epoch time (UNIX time) into Date again.It will give the same local date\time that pass from the UI.
Sample screenshot
Like charlietfl suggested, probably the global hack would be to override Date.prototype.toJSON() method, but that's not a good practice.
Where are you using your $http.post call? The best place to submit an $http request would be in a service. If you use a service, then I suggest you to enwrap your public service API, so that you could have "public" and "private" methods: these could be utilities to perform common operations, such as data transformations, validations..
angular.service('bookStoreService', ['$http'], function($http) {
var normalizeBooks = function(booksArray){
booksArray.forEach(function(book){
// do something on the book
});
};
var updateBooks = function(books){
normalizeBooks(books);
$http.post('myurl', books);
};
return {
updateBooks : updateBooks
};
});
Passing UTC date to server is desired behavior. The client APIs are supposed to handle UTC time instead of assuming the dates are all local dates.
But anyways, you can convert the date to string based on local time zone, and pass the string to server.
i think you just can pass it as string (if the api you use accept strings) with the format you need, let say "Tue Apr 04 2017 00:00:00 GMT+0530" and save it in back-end as string and then when you retrieve it, it will be string and so it will not be changed in any way.
Jindal saab, It will work like this. When we select any date with date picker or just pass any value it takes the original local date but when we pass that value further it converts it into UTC, thereafter it needs to convert to local zone again at receiving end. Database saves date-time in UTC format.
Did you added the angular-locale_en-in.js library to your app? Something like this....
angular.module('myAngularApp', [
'ngLocale'])
Otherwise, the js library won't have any effect in your angular application.
Append UTC at the end so that Browser converts it into UTC date
var dateToServer =new Date(dateFromUser+" UTC");
now the dateToServer will be UTC DateTime format.
Json serializer parse date from string. On a client the date properties are stored as local date in browser time zone. When you are posting your object to server all date properties converts to utc string. In most cases it is a properly behavor. But sometimes you need set and send date in a server time zone. Often it is need when you should set only date whitout time. In that case you should define string propertie and set it manualy. I usaly apply this trick.
class Obj{
d: Date
}
class ObjDto{
constructor(obj: Obj){
this.d= dateTimeToIsoLocalDateString(obj.d)
}
d: string
}
...
export function DateTimeToDate(date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
}
export function dateTimeToIsoLocalDateString(dateTime: Date): string {
if (dateTime === null) {
return null;
}
let date = DateTimeToDate(dateTime);
let res = date.toISOString().replace("Z", "");
return res;
}
For more understanding this theme you may learn this topic
//in res data of rest service in x the value is date in y value of y-axis
for (const i in res) {
console.log(i);
const a = {x: new Date(this.mimikatzlog[i].x), y: this.mimikatzlog[i].y};
this.policies.push(a);

Update date time string in Javascript to match current timezone using MomentJS

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.

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;

Pull date from mongo _id on the client side

I use my document _id client-side as strings. I would love to be able pull the timestamp from this value as you can on the server. Is it possible to recreate this functionality on the client side? (recast as objectid, or create a standalone function to pull this data)
example _id: "4f94c2a11a6bbec3872cb315"
Thanks!
How about this, broken down into steps... unfortunately it's only second resolution time that gets stored in the ObjectID.
var id = "4f94c2a11a6bbec3872cb315"​;
// first 4 bytes are the timestamp portion (8 hex chars)
var timehex = id.sub​string(0,8);
console.log(timehex); // gives: 4f94c2a1
// convert to a number... base 16
var secondsSinceEpoch = parseInt(timehex, 16);
console.log(secondsSinceEpoch); // gives: 1335149217
// convert to milliseconds, and create a new date
var dt = new Date(secondsSinceEpoch*1000);
console.log(dt);​ // gives: Sun Apr 22 2012 22:46:57 GMT-0400 (EDT)
See jsfiddle if you want to test: http://jsfiddle.net/pZdyM/
NOTE: this is kind of kludgy--it depends on the current ObjectID format. They might move the timestamp around within the ObjectID one day, and that would break this.

Categories