beingbecoming
beingbecoming

Reputation: 73

Month/Day comparison in Javascript

I'm not an expert in JavaScript, but I've been tasked with migrating a very large website that was coded into PHP into a new CMS that does not allow server-side languages. I am therefore spending my days converting many PHP date-calcs to JavaScript.

Something very simple in PHP:

<?php 
if (date('md') < 816) {$award_year = date('Y');}
if (date('md') > 815) {$award_year = date('Y') + 1;}
/*echo "year ".$award_year;*/
?>

This allows the year an application is due to automatically change to next year after August 15.

I've been trying to recreate this effect with Javascript and here is what I have come up with:

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

currDate = mmdd;
var currDate = new Date(); 
var appDate = new Date("0816");

if (currDate < appDate){
var printDate = theDate.getFullYear();  
}

else if (currDate >= appDate){
var printDate = theDate.getFullYear()+1;      
}

I know that I am missing something, because the var currDate cannot just = mmdd and then be compared to another date. Can someone help me with the next step here ? I'm trying to actually learn JavaScript as I go rather than just blindly fix issues.

Upvotes: 1

Views: 77

Answers (3)

Reza Saadati
Reza Saadati

Reputation: 5419

This will look similar to your PHP code:

const date = new Date();
const day = date.getUTCDate();
const month = date.getMonth();
const md = month + "" + day;

if (md < 816) {
	var award_year = date.getFullYear();
}
else if (md > 815) {
	var award_year = date.getFullYear() + 1;
}

console.log(award_year);

Upvotes: 3

user416
user416

Reputation: 536

I know there is plenty of things to improvise the below code... I am leaving it for you to improvise...

var today = new Date();
var mm = today.getMonth()+1; //January is 0! 
var dd = today.getDay();
if (mm < 10) {
    mm = '0'+mm
} 
var yyyy="2018"

var currDate = new Date(yyyy+"-"+mm+"-"+dd); 
var appDate = new Date("2018-01-16");

alert("appDate"+appDate);
alert("currDate"+currDate);

if (currDate < appDate){
var printDate = currDate.getFullYear();  
alert(printDate);
}
else if (currDate >= appDate){
var printDate = appDate.getFullYear()+1;    
alert(printDate);
    } 

Upvotes: 1

Craig Ayre
Craig Ayre

Reputation: 1173

Instead of combining strings and comparing two dates you could check the current day and month to determine which year to return.

For example,

function getAwardYear() {
  const today = new Date()
  const AUGUST = 7

  if (today.getMonth() >= AUGUST && today.getDate() > 15) {
    return today.getFullYear() + 1
  }

  return today.getFullYear()
}

// Today: 6th Jun 2018
getAwardYear() // 2018

// Today: 16th Aug 2018
getAwardYear() // 2019

Upvotes: 3

Related Questions