使用javascript的日和年

时间:2018-04-18 19:25:55

标签: javascript html

我正在做一个计划,在一年中的某一天,建立日期和月份。

我编写了这段代码,但当输入值> 31时,它无法正常工作。 我希望有人会帮助我,谢谢你。

<script>


var dayn=[31,28,31,30,31,30,31,31,30,31,30,31];
var vettmonth=["January", "February", "March", "April", "May","June","July","August","September","October","November","Dicember"];

function f()
    {
    var nday, day, month, count=0;

    nday=eval(ngiorno.value);

    for(var i=0;i<12;i++){
       if (nday>dayn[i]){
          count=count+dayn[i]; }
       else if(nday<32){
          day=nday;
          month=vettmonth[i]; 
          break;
       } 
       else if(nday>31 && nday<dayn[i+1]+count){
          day=nday-count;
          month=vettmonth[i+1]; 
          break;
       } 
    }

    mmese.value=month;
    ggiorno.value=day;      

}
</script>

2 个答案:

答案 0 :(得分:2)

你已经让它变得更复杂了。你可以这样做:

&#13;
&#13;
const vettmonth=["January", "February", "March", "April", "May","June","July","August","September","October","November","Dicember"];


let dayOfTheYear = 120;
let date = new Date(new Date().getFullYear(), 0, 1); // Start of this year
date.setDate(120); // increase the date by "dayOfTheYear"
console.log("Month:",vettmonth[date.getMonth()], "Day:", date.getDate());
&#13;
&#13;
&#13;

如果您不使用Date个对象,则可以这样做:

&#13;
&#13;
const dayn = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const vettmonth = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

let dayOfTheYear = 120;
let monthIndex = 0;
let day = 0;

for(let i = 0, sum = 0; i < dayn.length; i++){
  sum+=dayn[i];
  if(dayOfTheYear <= sum){
    monthIndex = i;
    day = (sum - dayOfTheYear) + 1;
    break;
  }
}

console.log("Month:", vettmonth[monthIndex], "Day:", day);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

问题是,在经历这几个月之后,你永远不会减少nday。因此,如果nday > 31nday > dayn[i]每次都为真,那么您永远不会执行设置else ifday的{​​{1}}块。您需要从month中减去dayn[i]

不需要两个nday块。当else if阻止失败时,您将在正确的月份内完成。并且也不需要if变量。

&#13;
&#13;
count
&#13;
&#13;
&#13;