使用JavaScript循环整整一年而不显示时间

时间:2015-06-28 18:24:44

标签: javascript

我试图让一种资源规划经理基本上是一种日历。我需要整整一年。

我有以下代码:

for (var x = 0; x < 365; x++){
    var today = new Date(2015, 01, x);
    document.write(today + "<br />");
}

它是我想要的那种但是我只想显示日期,日期,月份和年份,现在它也显示了时间。如何隐藏时间。检查此链接以查看我的结果(http://gyazo.com/3df91f5292072a54415d13b2ccca4922

2 个答案:

答案 0 :(得分:1)

您可以获得所需日期的一部分。例如:

var weekday = new Array(7);
weekday[0]=  "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

function formatDate(date) {
 var month = date.getUTCMonth() +1;
 var dayNumber = date.getUTCDate();
 var year = date.getUTCFullYear();
 var day = date.getUTCDay();
 return year + "-" + month + "-" + dayNumber + " " + weekday[day];
}

所以你的代码变成了:

for (var x = 0; x < 365; x++){
    var today = formatDate(new Date(2015, 01, x));
    document.write(today + "<br />");
}

P.S。在计算月份时请注意+1。

链接:https://jsfiddle.net/ajsv5ge4/

答案 1 :(得分:0)

你可以使用像MomentJS这样的lib:

moment().format('MMMM Do YYYY')