我正在尝试创建一个脚本,如果今天的日期早于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>
现在的输出是“未定义的”。任何想法都将不胜感激!
发布于 2018-06-05 08:49:21
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_day
和Today_month
-因此您应该拥有所需的一切
发布于 2018-06-05 09:56:59
简化的条件是:如果月份不是1月(不是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 );
https://stackoverflow.com/questions/50690160
复制相似问题