beingbecoming
beingbecoming

Reputation: 73

JavaScript to change Year displayed based on month/day

I'm trying to create a script that if today's date is before January 16, the current year will print, but if today's date is greater than or equal to January 16, the following year will print.

I am pretty new to coding JavaScript so perhaps I am just missing something stupid. Can anyone help by looking over this code and tell me what I did wrong?

<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>

Then in the HTML:

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

Output right now is "undefined." Any ideas would be greatly appreciated!

Upvotes: 0

Views: 190

Answers (2)

Slai
Slai

Reputation: 22876

The simplified condition is: if month is not January (not 0), or date is after the 15th, then get next year:

var today = new Date, year = today.getFullYear();  

if (today.getMonth() || today.getDate() > 15) year++;

console.log( year );

Or a bit shorter on one line:

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

console.log( year );

Upvotes: 1

Dan
Dan

Reputation: 3815

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

this should start you on the right process - you need to compare each calendar item (first month, then day) to determine what you are looking for

all the variables you need:

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

you know how to get Today_day and Today_month - so you should have everything you need

Upvotes: 1

Related Questions