Danny
Danny

Reputation: 1003

Parse & format javascript date: dd M YYYY to YYYY-mm-dd

I have a date which looks like:

30 Apr 2015

How do I parse and display the date like this (without Moment.js)?

2015-04-31 (or YYYY-mm-dd)

Upvotes: 1

Views: 2097

Answers (4)

Egy Success
Egy Success

Reputation: 112

you can do that easy with

//define Date
    var xdate = "31 Apr 2015";
// simple array to define months from Jan to Dec [01 : 12]
    var months = {
    Jan:'01',
    Feb:'02',
    Mar:'03',
    Apr:'04',
    May:'05'
    };
// split our Date and rearrange as yyyy-mm-dd
    var reform = xdate.split(' ')[2]+'-'+months.Apr+'-'+xdate.split(' ')[0];
    alert(reform);// return 2015-04-31

Upvotes: 0

Pedro Lobito
Pedro Lobito

Reputation: 98871

Use moment.js

Convert your date like this:

var myDate = moment("30 Apr 15", "DD MMM YY").format("YYYY-MM-DD");
console.log(myDate);
//2015-04-30

DEMO

Upvotes: 0

Trott
Trott

Reputation: 70065

The easiest thing to do might be to use moment.js.

If you prefer rolling your own solution in vanilla JS, this will work:

var padZero = function (integer) { 
    return integer < 10 ? '0' + integer : '' + integer 
};

var myDate = new Date('30 Apr 2015');
var myDateString = myDate.getFullYear() + '-' + 
    (padZero(myDate.getMonth()+1)) + '-' + 
    (padZero(myDate.getDate()));

console.log(myDateString); // 2015-04-30

Upvotes: 4

S McCrohan
S McCrohan

Reputation: 6693

The parsing part is easy...though it'll fail on your example, because there is no 31st day in April :)

var x = new Date("30 Apr 2015");

Formatting the date is a little trickier. You have a few options. Date natively supports several output methods (.toDateString(), .toLocaleDateString(), etc) but none of them match the format you've given. It does, however, allow you to individually select the day, month and year values for the date. So, you can assemble them manually:

console.log(x.getFullYear() + '-' + (x.getMonth()+1) + '-' + x.getDate())

Note here that .getMonth() returns a 0-based index and isn't padded to two digits, and .getDay() gets the day-of-the-week index, not day-of-the-month (which is .getDate()).

However, your better choice is to take a look at moment.js, which provides the ability to format by an arbitrary format string, similar to what you'd expect from other languages. Unless you're unable to introduce another library for some reason, I feel this is a category of problem where it makes sense to use the very nice solution that already exists.

Upvotes: 2

Related Questions