3

I want to convert string in date format.

My String format is 30-Jul-2016 And want to convert into 2016-07-30. Only using javascript.

6 Answers 6

1

To be as dynamic as possible I advise to implement first Douglas Crockford's supplant function, and assign it to String Object's prototype (How can I do string interpolation in JavaScript?). Here's how you do it:

String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

After that, you can implement something like this:

function changeFormat(from, to){
    var months = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec'
    ];
    var date = new Date(from);
    return to.supplant({
        YYYY: date.getFullYear(),
        MMM: months[date.getMonth()],
        MM: date.getMonth()+1 > 9 ? date.getMonth()+1 : '0'+parseInt(date.getMonth()+1),
        DD: date.getDate() > 9 ? date.getDate() : '0' + parseInt(date.getDate())
    })
}

And this is how it would work:

changeFormat("30-Jul-2016","{YYYY}-{MM}-{DD}") // 2016-07-30

Example:

String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

function changeFormat(from, to){
    var months = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec'
    ];
    var date = new Date(from);
    return to.supplant({
        YYYY: date.getFullYear(),
        MMM: months[date.getMonth()],
        MM: date.getMonth()+1 > 9 ? date.getMonth()+1 : '0'+parseInt(date.getMonth()+1),
        DD: date.getDate() > 9 ? date.getDate() : '0' + parseInt(date.getDate())
    })
}

console.log(changeFormat("30-Jul-2016","{YYYY}-{MM}-{DD}"));

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

Comments

0

var d = new Date('30-Jul-2016'.split('-').join(' ')),
    dFormated = d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + d.getDate();

console.log(dFormated);

3 Comments

var d = new Date('30-Jul-2016') returns invalid date
Thanks @KeyurShah.. Updated answer
Yes it works after you edited and added split and join.
0

Another way:

function formatDate(string) {
  var date = new Date(string),
      dd = date.getDate(),
      mm = date.getMonth() + 1,
      yyyy = date.getFullYear();

  dd = dd < 10 ? '0' + dd : dd;
  mm = mm < 10 ? '0' + mm : mm;

  return yyyy + '-' + mm + '-' + dd;
}

console.log(formatDate('30-Jul-2016')); // 2016-07-30

2 Comments

var date = new Date(string) return invalid date
In your case it returns a valid Date object. "new Date('30-Jul-2016')" // Sat Jul 30 2016 00:00:00 GMT+0300 (MSK)
0

Without a library, like Moment, the best way would be to keep an array of months to get the numerical values (there's no guarantee every browser will parse that date), and then just split the string and parse it

var months = [
  'Jan',
  'Feb',
  'Mar',
  'Apr',
  'May',
  'Jun',
  'Jul',
  'Aug',
  'Sep',
  'Oct',
  'Nov',
  'Dec'
];

function pad(x) {return x < 10 ? '0' + x : x}; // zero padding

var str   = "30-Jul-2016";
var parts = str.split('-');
var date  = new Date(parts[2], months.indexOf(parts[1]), parts[0]);

// now you can output whatever

var new_date = date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate());

document.body.innerHTML = new_date;

Comments

0

Try this

var date = '30-Jul-2016';
date = date.split('-').join(' ');
var d = new Date(date);
alert(d.getFullYear() + '-'+(d.getMonth()+1) +'-'+ d.getDate());
console.log(d.getFullYear() + '-'+(d.getMonth()+1) +'-'+ d.getDate());

Comments

0

Try this code

var date = '30-Jul-2016';
date = date.split('-').join(' ');
var d = new Date(date);
    dd = d.getDate();
      mm = d.getMonth() + 1;
      yyyy = d.getFullYear();

  dd = dd < 10 ? '0' + dd : dd;
  mm = mm < 10 ? '0' + mm : mm;
alert(yyyy + '-'+mm +'-'+ dd);

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.