Skip to content

Instantly share code, notes, and snippets.

@MohiuddinSumon
Created July 22, 2019 17:15
Show Gist options
  • Save MohiuddinSumon/37533f66fda9512b8e409d26530681f1 to your computer and use it in GitHub Desktop.
Save MohiuddinSumon/37533f66fda9512b8e409d26530681f1 to your computer and use it in GitHub Desktop.
Get Day From Date with Javascript
// https://www.quora.com/How-do-I-calculate-the-day-from-dates
// implemented algo from Aayush-Chaudhry
const DAYS = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday'];
function getDate(date)
{
var brokenDate = date.split(" ");
var givenDate = parseInt(brokenDate[0]);
var givenMonth = brokenDate[1].toLowerCase();
//console.log(givenMonth);
var givenYear = parseInt(brokenDate[2]);
//console.log(givenDate);
var monthNumber = getMonthNumber(givenMonth,givenYear);
//console.log(monthNumber);
var f = parseInt(givenYear/100);
var l = parseInt(givenYear-(f*100));
var l4 = parseInt((givenYear-(f*100))/4);
var century = getCentury(f);
// console.log(f+' '+l+' '+l4+' '+century);
var res = (givenDate+monthNumber+century+l4+l)%7;
console.log("Given Date is "+DAYS[res]);
}
function leapYearCheck(year)
{
if( (year%100 !== 0 && year%4 === 0) || year%400 === 0) return true;
else return false;
}
function getMonthNumber(givenMonth,givenYear)
{
if(leapYearCheck(givenYear))
{
//6 2 3 6 1 4 6 2 5 0 3 5
//console.log("It's a Leap Year "+givenMonth);
if( 'january april july'.search(givenMonth) !== -1 ) return 6;
if( 'february augest'.search(givenMonth) !== -1 ) return 2;
if( 'march november'.search(givenMonth) !== -1 ) return 3;
if( 'may'.search(givenMonth) !== -1 ) return 1;
if( 'june'.search(givenMonth) !== -1 ) return 4;
if( 'september december'.search(givenMonth) !== -1 ) return 5;
if( 'october'.search(givenMonth) !== -1 ) return 0;
}
else {
//0 3 3 6 1 4 6 2 5 0 3 5
if( 'january october'.search(givenMonth) !== -1 ) return 0;
if( 'february march november '.search(givenMonth) !== -1 ) return 3;
if( 'april july'.search(givenMonth) !== -1 ) return 6;
if( 'may'.search(givenMonth) !== -1 ) return 1;
if( 'june'.search(givenMonth) !== -1 ) return 4;
if( 'augest'.search(givenMonth) !== -1 ) return 2;
if( 'september december'.search(givenMonth) !== -1 ) return 0;
}
}
function getCentury(num){
if(num%4 == 0) return 6;
else if(num%4 == 1) return 4;
else if(num%4 == 2) return 2;
else if(num%4 == 3) return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment