JavaScript日期/时间转换

时间:2011-11-04 17:31:33

标签: javascript datetime

我在数据库中有以下格式的日期和时间:

2011-08-02T00:00:00-00:00

将它们转换为8-2-2011之类的最简单方法是什么?

谢谢,

4 个答案:

答案 0 :(得分:1)

以下是代码:

x=new Date("2011-08-02T00:00:00-00:00")
str=(x.getUTCMonth()+1)+"-"+x.getUTCDate()+"-"+x.getUTCFullYear()

或者:

x="2011-08-02T00:00:00-00:00"
x=/^(\d+)\-(\d+)\-(\d+)/.exec(x)
if(x){
   str=(parseInt(x[2],10)+"-"+parseInt(x[3],10)+"-"+parseInt(x[1],10))
}

答案 1 :(得分:1)

var date = "2011-08-02T00:00:00-00:00".split('T')[0].split('-').reverse();
var month = date[0], day = date[1];

//remove 0 in the beginning if not necessary
if (+month < 10) {
    month = month.slice(1);
}
if (+day < 10) {
    day = day.slice(1);
}

//swap between the two
date[0] = day;
date[1] = month;

date.join('-');

或者你可以使用枯燥的Date方式。

答案 2 :(得分:0)

此格式适用于Javascript Date构造函数:

var d = new Date("2011-08-02T00:00:00-00:00");
var month = d.getUTCMonth() + 1;
var day = d.getUTCDate();
var year = d.getUTCFullYear();

var output = month + "-" + day + "-" + year;

答案 3 :(得分:0)

一种方法可能是分割日期部分

var date = "2011-08-02T00:00:00-00:00";

var dpart = (date.substr(0,10)).split("-");

var odate = parseInt(dpart[1],10)+"-"+parseInt(dpart[2],10)+"-"+dpart[0];