Javascript momentjs convert UTC from string to Date Object
Asked Answered
H

2

3

Folks, Having a difficult time with moment.js documentation.

record.lastModified = moment.utc().format();

returns:

2014-11-11T21:29:05+00:00

Which is Great, its in UTC... When I store that in Mongo, it gets stored as a String, not a Date object type, which is what i want.

What I need it to be is:

"lastModified" : ISODate("2014-11-11T15:26:42.965-0500")

But I need it to be a native javascript object type, and store that in Mongo. Right now if i store the above, it goes in as string, not Date object type.

I have tried almost everything with moment.js. Their toDate() function works, but falls back to my local timezone, and not giving me utc.

Thanks!

Hodometer answered 11/11, 2014 at 21:34 Comment(3)
The toDate() function that you mention is what you want here. JavaScript Date objects always internally represent their time in UTC. Can you edit your question with the details on why you think that's not working?Delouse
Try new Date(moment.utc().format());Imago
I am having the same issue, been at this for hoursHyetograph
D
5

Saving a Javascript Date object will result in an ISODate being stored in Mongo.

Saving an ISO date as a Javascript String will result in a String being stored in Mongo.

So, this is what you want: record.lastModified = new Date(moment().format());

Deductible answered 19/8, 2015 at 17:45 Comment(0)
H
0

Not an ideal solution, But I achieved the same result, by manually converting it to ISODate object through monogo shell. We need the ISODate for comparison/query for aggregating results, so we run this script before running our aggregate scripts.

Inserting local time string by using moment().format().

"createdDt" : "2015-01-07T17:07:43-05:00"`

Converting to an ISODate (UTC) with:

    var cursor = db.collection.find({createdDt : {$exists : true}});
    while (cursor.hasNext()){
        var doc = cursor.next();
        db.collection.update(
                   {_id : doc._id}, 
                   {$set: {createdDt : new ISODate(doc.createdDt)}})
    }

results in

"createdDt" : ISODate("2015-01-07T22:07:43Z")"

Note the time got converted T17:07:43-05:00 to T22:07:43Z

I could not find any solution for inserting BSON ISODate format (which is UTC by default) from JavaScript directly, while inserting a new document, it seems to be available through pyMongo & C#/Java Drivers though. Trying to look for an maintainable solution

Halide answered 7/1, 2015 at 22:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.