将m-yyyy格式转换为字符串

时间:2015-08-05 15:51:27

标签: javascript date

我有一个像这样的日期格式

ToList

如何将其转换为在屏幕上显示为“2015年5月”?

3 个答案:

答案 0 :(得分:1)

您可以尝试使用MomentJS http://momentjs.com/这是Javascript的日期/时间库。我相信语法是moment(yourDate, 'M-YYYY').format('MMM YYYY');

如果你想自己动手:

function format(date) {
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

    var month = date.substring(0, date.indexOf('-'));
    var year = date.substring(date.indexOf('-') + 1);

    return months[parseInt(month) - 1] + ' ' + year;
}

var formatted = format('5-2015');

答案 1 :(得分:0)

假设您的所有日期都采用“5-2015”的格式(例如6-2015或12-2015),您可以使用javascript上的split函数将字符串值拆分为数月和数年。< / p>

例如:

var date = "5-2015";
date.split("-"); //splits the date whenever it sees the dash
var month;
if(date[0] == "5"){ //accesses the first split value (the month value) and check if it's a month.
    month = "May";
} //do this with the rest of the months.
var finalString = month + " " + date[1]; //constructs the final string, i.e. May 2015
alert(finalString);

答案 2 :(得分:0)

你可以这样:

&#13;
&#13;
function parseDate(dateString) {
  var d = dateString.split("-"); // ["5", "2015"]
  // Month is 0-based, so subtract 1
  var D = new Date(d[1], d[0]-1).toString().split(" "); // ["Fri", "May", "01", "2015", "00:00:00", "GMT+0200", "(Central", "Europe", "Daylight", "Time)"]
  return D[1] + " " + D[3];
}

(function() {
  alert(parseDate("5-2015"));
}());
&#13;
&#13;
&#13;