0

我有这个问题。我通过 AJAX 调用从 .NET 服务获取日期。得到的日期格式是这样的(我在意大利)

Mon Dec 31 2012 08:25:21 GMT+0100 (ora solare Europa occidentale)   

如何以 dd/MM/yyyy 格式格式化此日期?我不能在 .NET 服务端工作,而只能从 JS 端工作。提前致谢。

4

3 回答 3

0

假设您的输入格式没有改变:

var date = "Mon Dec 31 2012 08:25:21 GMT+0100 (ora solare Europa occidentale)"
var parts = date.split(' ');
var monthMap = {"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"}
var formatted = parts[2]+"/"+monthMap[parts[1]]+"/"+parts[3]

// -> 31/12/2012
于 2013-03-13T08:36:23.973 回答
0

您可以使用正则表达式来解析日期,然后将这些位重新组合成所需的格式。

function pad(n) {
    return (n < 10) ? ("0" + n) : n;
}


var dateString = "Mon Dec 31 2012 08:25:21 GMT+0100 (ora solare Europa occidentale)";

// I'm not sure what the Italian three letter month abbreviations are, so I've used English
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

var m = dateString.match(/^\S{3} (\S{3}) (\d{1,2}) (\d{4})/);

var formattedDate = pad(m[2]) + "/" + pad(months.indexOf(m[1])+1) + "/" + m[3];

JSFiddle在这里:http: //jsfiddle.net/Mhuxk/

于 2013-03-13T08:36:54.827 回答
0

您可以相当轻松地解析这些位以获取日期对象,然后以您想要的任何格式创建格式化字符串。以下考虑了可能与客户端不同的时区:

var s = 'Mon Dec 31 2012 08:25:21 GMT+0100';

function getDate(s) {

    // Split the string into bits
    var s = s.split(/[ :]/);

    // Conversion for month to month number (zero indexed)
    var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,
                  jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};

    // Calculate the offset in minutes
    var offsetMins = s[7].substring(4,6) * 60;
    offsetMins += s[7].substring(6,8) * 1;
    offsetMins *= s[7].substring(3,4) == '+'? 1 : -1;

    // Build a UTC date value, allowing for the offset in minutes,
    // and pass to the Date constructor
    var date = new Date(Date.UTC(s[3], months[s[1].toLowerCase()],
               s[2], s[4], (s[5] - offsetMins), s[6]));

    // return the date object
    return date;
}

function padN(n) {
  return (n<10? '0' : '') + n;
}

var d = getDate(s);

alert(padN(d.getDate()) + '/' + padN(d.getMonth() + 1) + '/' + d.getFullYear()); 
于 2013-03-13T08:57:26.633 回答