5

I have a mongodb set up and I'm storing date and time alongside other data. The problem is that when I receive the data back the date and time is in a strange format and I'm not sure how I can handle this with JavaScript or jQuery.

my schema:

var carSchema = mongoose.Schema ({
    carType: String,
    notes: String,
    created: {type: Date, default: Date.now}
});

this is what I'm getting in the JavaScript object:

created: "2015-03-15T14:01:16.447Z"

How can I convert this to Time and date?

Can anyone help please?

1
  • 6
    it's a valid date string anyway: var d=new Date("2015-03-15T14:01:16.447Z"); alert(d.toLocaleString()) Commented Mar 17, 2015 at 23:31

2 Answers 2

3

Here i am giving some snippet of codes which will assist to getting your requirement.

var created_date = new Date(carSchema.created);

var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = created_date.getFullYear();
var month = months[created_date.getMonth()];
var date = created_date.getDate();
var hour = created_date.getHours();
var min = created_date.getMinutes();
var sec = created_date.getSeconds();
var time = date + ',' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;    // final date with time, you can use this according your requirement



Or

var timestamp = created_date.getTime();    // get time stamp, now you can convert date and time from it using simple JavaScript function

You can use time() npm to reset timezone for this

var time = require('time');

created_date.setTimezone("Australia/Sydney");

Thanks

Sign up to request clarification or add additional context in comments.

1 Comment

Great, thanks. However, you need to create a for loop i < 10 to add zeros in seconds, minutes and hours otherwise you will get time like this: 11:3:4 instead of 11:03:04
1

Simple:

var myNewJSDateObj = new Date(carSchema.created);
var someOtherDateTimeVar = myNewJSDateObj.to...

where:

myNewJSDateObj.toDateString(        myNewJSDateObj.toLocaleDateString(  myNewJSDateObj.toString(            myNewJSDateObj.tojson(
myNewJSDateObj.toGMTString(         myNewJSDateObj.toLocaleString(      myNewJSDateObj.toTimeString(
myNewJSDateObj.toISOString(         myNewJSDateObj.toLocaleTimeString(  myNewJSDateObj.toUTCString(

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.