添加整数天到目前为止,然后是getDay(),getMonth(),GetFullYear()

时间:2015-03-03 15:37:13

标签: javascript date

任何人都可以帮助我。我希望从滑块中获取整数并将它们添加到日期并将日期格式设置为“2015年3月27日星期五”,当我更改滑块时它将更改日期和日期。我有这个代码,但有滑块它不起作用。我想修改这段代码,

var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September",
        "October", "November", "December");

 var day = new Array("1st", "2nd", "3rd", "4th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "18th", "19th", "20th"
                , "21st", "22nd", "23rd", "24th", "26th", "27th", "28th", "29th", "30th", "31st");

            var WeekDay = new Array("Saturday", "Sunday", "Monday", "TuesDay", "Wednesday", "Thursday", "Friday");

            var newdate = document.getElementById("slider").value = value;


            // 

            var d = new Date();

            d.setDate(d.getDate() + newdate);

            document.getElementById("date").innerHTML = WeekDay[d.getDay()] + " " + day[d.getDay()] + " " + m_names[d.getMonth()] + " " + d.getFullYear();

1 个答案:

答案 0 :(得分:0)

setDate方法设置月份的日期。它没有"神奇地"如果,例如,今天是3月3日,并且你向柜台增加了70天,那么下个月会溢出。

<强>然而

您可以获得一个名为moment的库,这对于完成这类工作非常有帮助。我推荐这个而不是重新发明轮子的原因是因为它会花费你很多工作来考虑:

  • 长度不同的月份
  • 闰年
  • ...

因此。获取时刻(使用凉亭,npm或者你正在使用的任何东西。或者只是在这里:http://momentjs.com/)。然后代码的最后一部分变为:

// Pre-setting values
var newdate = 173;

var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

var day = new Array("1st", "2nd", "3rd", "4th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "18th", "19th", "20th" , "21st", "22nd", "23rd", "24th", "26th", "27th", "28th", "29th", "30th", "31st");

var WeekDay = new Array("Saturday", "Sunday", "Monday", "TuesDay", "Wednesday", "Thursday", "Friday");


var d = moment(new Date());
d.add(newdate, 'days');

document.getElementById("date").innerHTML = WeekDay[d.day()] + " " + day[d.date()] + " " + m_names[d.month()] + " " + d.year();

在这里小提琴:http://jsfiddle.net/q8ms5us2/1/

请注意,当时还有一个语言环境库,当涉及到其他语言或日期时间格式时,您可能需要查看这些库以使代码易于适应...