Madasu K
Madasu K

Reputation: 1863

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 the above date should be : "20150325"

Upvotes: 2

Views: 1542

Answers (4)

Adrian
Adrian

Reputation: 8597

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 = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
var dateFormated = someDate.toISOString().substr(0,10).replace(/-/g,"");
    
alert(dateFormated);

Upvotes: 4

Paolo
Paolo

Reputation: 15827

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 = new Date( 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

Upvotes: 3

Daniel Taub
Daniel Taub

Reputation: 5359

function getFormattedDate(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(new Date());

Upvotes: 3

Osama
Osama

Reputation: 3040

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-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};
var date = new Date();
date.yyyymmdd();

Upvotes: 5

Related Questions