spogebob92
spogebob92

Reputation: 1484

Formatting String to Date in JS

I'm sure this is a simple question, but I can't for the life of me solve it.

I have a JSON object as so:

    {
    "_id": {
        "$oid": "57cb5aac9bd9a31100c793d1"
    },
    "reminders": [
        "2014-03-12T12:00:00",
        "2014-03-12T13:37:27",
        "2014-03-12T13:37:27",
        "2014-03-12T22:14:27"
    ],
    "user": "xxx"
}

I want to parse the date from the reminders is JS to a date object in a loop, as so.

for (var i = userSchedule.reminders.length - 1; i >= userSchedule.reminders.length - 1; i++)
    {
    var date = new Date(userSchedule.reminders[i]);
    }

But it just displays invalid date whenever I log it. Any ideas?

Upvotes: 1

Views: 90

Answers (4)

RobG
RobG

Reputation: 147413

Your loop is broken, it seems you're trying to iterate from 0 to userSchedule.reminders.length - 1, so:

for (var i=0; i < userSchedule.reminders.length; i++) {
  // do stuff
}

Also, parsing date strings with the Date constructor (and Date.parse, they are equivalent for parsing) is not recommended due to variances in implementations. You should parse the string manually, a library can help but isn't necessary if you have only one format to parse.

A date string like "2014-03-12T12:00:00" should be treated as "local" (i.e. the host time zone offset should be used when calculating the time value), however not all implementations will do that. A small library like fecha.js makes it simple:

var d = fecha.parse('2014-03-12T12:00:00','YYYY-MM-DDTHH-mm-ss');

You can also use moment.js, but it's likely overkill for what you need. There are many other parsing and formatting libraries available that are suitable too.

Upvotes: 0

Ash
Ash

Reputation: 620

Something here is not as it seems, because calling the date constructor in both Chrome and Node.JS returns the correct date for me. I also tried it in the JSBin below.

https://jsbin.com/fomagugiwe/edit?html,output

I would log the value going into the date constructor, just to ensure that the value being used is of the correct format. Could you also provide the Node version you are using for this script for further testing..

Upvotes: 1

Fareed Alnamrouti
Fareed Alnamrouti

Reputation: 32154

for date time manipulation I strongly recommend using http://momentjs.com

where you can do

moment("your date string") 

Or

moment("your date string","your date format") 

Upvotes: 1

Manoj
Manoj

Reputation: 347

Though its not answer but why have you used user_schedule.reminders and userSchedule.reminders and your for loop will loop only once with correct data since your loop begins with i=3; which is index for last element of userSchedule.reminders[3] and when you loop next it will go beyond the scope of your array reminders

Upvotes: 4

Related Questions