简体   繁体   中英

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

?

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/

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)");

Without a formatter, go for:

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

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...");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM