Skip to content Skip to sidebar Skip to footer

Convert Date Format To 'yyyymmdd'

In Javascript, I have date string as shown below: var dateStr = 'Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)'; I need to convert it to 'YYYYMMDD' format. For example

Solution 1:

A good function for doing that which I found and used it always.

Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-basedvar dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};
var date = newDate();
date.yyyymmdd();

Solution 2:

Here's a dirty hack to get you started. There are numerous ways of achieving the format you want. I went for string manipulation (which isn't the best performance).

var someDate = newDate("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
var dateFormated = someDate.toISOString().substr(0,10).replace(/-/g,"");
    
alert(dateFormated);

Solution 3:

functiongetFormattedDate(date) {
  var year = date.getFullYear();

  var month = (1 + date.getMonth()).toString();
  month = month.length > 1 ? month : '0' + month;

  var day = date.getDate().toString();
  day = day.length > 1 ? day : '0' + day;

  return year + month + day;
}

And then just call the function :

alert(getFormattedDate(newDate());

Solution 4:

The Date object is able to parse dates as string d = new Date( dateStr ); provided that they are properly formatted like the example in your question.

The Date object also offers methods to extract from the instance the year, month and day.

It's well documented and there are plenty of examples if you just Google for it.


What is worth mentioning is that the Date object doesn't handle timezone and the internal date-time is always converted into the client's timezone.

For example here's what I get if I try to parse your date in my browser (I'm in GMT+01):

dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
d =newDate( dateStr );

---> Wed Mar 25 2015 01:00:00 GMT+0100 (CET) = $2

If you need to handle timezone properly the easiest way is to use a library like MomentJS

Post a Comment for "Convert Date Format To 'yyyymmdd'"