繁体   English   中英

JavaScript根据月/日更改显示的年份

[英]JavaScript to change Year displayed based on month/day

我正在尝试创建一个脚本,如果今天的日期在1月16日之前,则将打印当前年份,但是如果今天的日期大于或等于1月16日,则将打印第二年。

我对JavaScript编码很陌生,所以也许我只是缺少一些愚蠢的东西。 谁能帮忙查看一下这段代码,并告诉我我做错了什么?

<script type="text/javascript">
var today = new Date();
var mm = today.getMonth()+1; //January is 0! 
var dd = today.getday();
if (mm < 10) {
    mm = '0'+mm
} 

var today = new Date("mm/dd") 
var other = new Date("01/16")

if (today < other){
var printDate = theDate.getFullYear();  
}

else if (today >= other){
var printDate = theDate.getFullYear()+1;      
}
</script>

然后在HTML中:

<strong>16 January</strong> <script>document.write(printDate);</script>

现在的输出是“未定义”。 任何想法将不胜感激!

var today = new Date("mm/dd") // Invalid Date
var other = new Date("01/16") // Tue Jan 16 2001 00:00:00 GMT-0800 (PST)

这应该使您开始正确的流程-您需要比较每个日历项(第一个月,然后是天)以确定您要查找的内容

您需要的所有变量:

var Today_day = (integer)
var Today_month = (integer)
var Compare_day = (integer) 16 // or 15? not sure about base 0 for a day
var Compare_month = (integer) 0

您知道如何获取Today_dayToday_month因此您应该拥有所需的一切

简化的条件是:如果月份不是一月(不是0),或者日期在15日之后,则获得下一年:

 var today = new Date, year = today.getFullYear(); if (today.getMonth() || today.getDate() > 15) year++; console.log( year ); 

或在一行上短一点:

 var date = new Date, year = date.getFullYear() + (date.getMonth() || date.getDate() > 15) console.log( year ); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM