在Javascript中格式化日期

时间:2014-02-04 17:21:56

标签: javascript

我如何采用这种格式的字符串:

2014-06-12T23:00:00

并在Javascript中将其格式化为:

12/06/2014 23:00

3 个答案:

答案 0 :(得分:1)

正如@ Xotic750所说的那样,它只是解析ISO8601时间戳:

formatMyDate = function(dt, dayFirst){
    var year = dt.getFullYear().toString();
    //month starts from zero
    var month = (dt.getMonth()+1).toString();
    var date  = dt.getDate().toString();
    var result = null;
    if(dayFirst)
        result = (date[1]?date:"0"+date[0]) + "/" + (month[1]?month:"0"+month[0]);
    else
        result = (month[1]?month:"0"+month[0]) + "/" + (date[1]?date:"0"+date[0]);
    result += "/" + year + " " + dt.toTimeString().split(" ")[0];
    return result;
}
parseUTCTimestamp = function(dtstr) {
    var dt = null;
    var dtArr = dtstr.split(/[\-T:]/);
    dt = new Date(Date.UTC(parseInt(dtArr[0]), dtArr[1]-1, parseInt(dtArr[2]), parseInt(dtArr[3]), parseInt(dtArr[4]), parseInt(dtArr[5])));

    return formatMyDate(dt);
};
parseTimestamp = function(dtstr) {
    var dt = null;
    var dtArr = dtstr.split(/[\-T:]/);
    dt = new Date(parseInt(dtArr[0]), dtArr[1]-1, parseInt(dtArr[2]), parseInt(dtArr[3]), parseInt(dtArr[4]), parseInt(dtArr[5]));

    return formatMyDate(dt, true);
};

parseUTCTimestamp("2014-06-12T23:00:00");//-->"06/13/2014 03:30:00"

parseTimestamp("2014-06-12T23:00:00");//-->"12/06/2014 23:00:00"

答案 1 :(得分:0)

使用Javascript的内置日期方法:

function getDateString() {
    var d = new Date('2014-06-12T23:00:00');   // pass in your date string
    var y = d.getFullYear();  // the full year (4 digits)
    var m = d.getMonth() + 1; // 0-based month

    var dt = d.getDate() + 1;     // 0-based day of the month
    dt = dt < 10 ? '0' + dt : dt; // add a preceding 0 to numbers less than 10      

    var h = d.getHours();     // 0-based hours
    h = h < 10 ? '0' + h : h; // add a preceding 0 to numbers less than 10

    var mn = d.getMinutes();      // minutes
    mn = mn < 10 ? '0' + mn : mn; // add a preceding 0 to numbers less than 10

    return m + '/' + dt + '/' + y + ' ' + h + ':' + mn;
}

答案 2 :(得分:0)

在这种情况下,完全避免Date对象可能更简单,正如@Ismael建议的那样,使用直接字符串操作。

的Javascript

var dateStamp = '2014-06-12T23:00:00',
    dateTime = dateStamp.split('T'),
    date = dateTime[0].split('-'),
    time = dateTime[1].split(':'),
    formatted = date.reverse().join('/') + ' ' + time.slice(0, -1).join(':');

console.log(formatted);

输出

12/06/2014 23:00

jsFiddle