2

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

?

herman
  • 11,740
  • 5
  • 47
  • 58
happydev
  • 161
  • 1
  • 8
  • 2
    possible duplicate, see http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript/1056730#1056730 – herman Jun 25 '13 at 15:45

4 Answers4

3

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/

Mr. B.
  • 8,041
  • 14
  • 67
  • 117
  • 2
    Loading a whole library solely to get the date is totaly stupid. Unless he really wants to work a lot with the time and date he should stay away from that, performance wise. – Jeff Noel Jun 25 '13 at 15:51
  • 1
    @Ghillied Of course he shouldn't load a library just for this simple task. But why should I post an answer twice? It's just another solution and maybe the right one if he didn't know momentjs yet. :-) – Mr. B. Jun 25 '13 at 16:01
1
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)");
Doug
  • 3,312
  • 1
  • 24
  • 31
1

Without a formatter, go for:

('0' + date.getDate()).slice(-2) + '.' +
('0' + (date.getMonth() + 1)).slice(-2) + '.' + 
date.getFullYear()
nekaab
  • 442
  • 3
  • 15
0

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...");
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177