happydev
happydev

Reputation: 161

JS. Convert format date

I have date in this format:

var date:

Fri May 31 2013 17:41:01 GMT+0200 (CEST)

How to convert this to: 31.05.2013

?

Upvotes: 2

Views: 9453

Answers (4)

Mr. B.
Mr. B.

Reputation: 8717

EDIT: This answer is good if you've to handle dates and times often. Maybe it's what you're looking for. It made my work much easier. It's worth a look. If it's just about this simple task, don't load a new script.

I recomment moment.js: http://momentjs.com/

Simple coded example:

var date = new Date("Fri May 31 2013 17:41:01 GMT+0200 (CEST)");
var date_str = moment(date).format("DD.MM.YYYY");
alert(date_str);

Try it: http://jsfiddle.net/bvaLt/

Upvotes: 3

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123428

If d is a Date Object (and not a string representing the date) you may use this approach

var d = new Date();

("0" + d.getDate()).slice(-2) + "." + 
("0" + (d.getMonth() + 1)).slice(-2) + "." + 
d.getFullYear();

otherwise, if you have a string, as a first step just pass it into the Date constructor as argument

var d = new Date("Fry May 31...");

Upvotes: 0

nekaab
nekaab

Reputation: 442

Without a formatter, go for:

('0' + date.getDate()).slice(-2) + '.' +
('0' + (date.getMonth() + 1)).slice(-2) + '.' + 
date.getFullYear()

Upvotes: 1

Doug
Doug

Reputation: 3312

function convertDate(str){
  var d = new Date(str);
  return addZero(d.getDate())+"."+addZero(d.getMonth()+1)+"."+d.getFullYear();
}

//If we have the number 9, display 09 instead
function addZero(num){
  return (num<10?"0":"")+num;
}

convertDate("Fri May 31 2013 17:41:01 GMT+0200 (CEST)");

Upvotes: 1

Related Questions