Skip to content

Instantly share code, notes, and snippets.

@alvachien
Created August 22, 2017 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alvachien/a9f627d55ca4d2e51a0d025079ff348d to your computer and use it in GitHub Desktop.
Save alvachien/a9f627d55ca4d2e51a0d025079ff348d to your computer and use it in GitHub Desktop.
Date-relevant methods in Javascript
//
// Date related functions
//
function isLeapYear(year) {
return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
}
function getLastDay(year, month) {
var new_year = year;
var new_month = month++;
if (month > 12)
{
new_month -= 12;
new_year++;
}
var new_date = new Date(new_year, new_month, 1);
return (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate();
}
function getMonthDays(year, month) {
return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] || (isLeapYear(year) ? 29 : 28);
}
function getDaysInMonth(year, month) {
month = parseInt(month, 10) + 1;
var temp = new Date(year + "/" + month + "/0");
return temp.getDate();
}
function getWeekNumber(y, m, d) {
var now = new Date(y, m - 1, d),
year = now.getFullYear(),
month = now.getMonth(),
days = now.getDate();
for (var i = 0; i < month; i++) {
days += getMonthDays(year, i);
}
var yearFirstDay = new Date(year, 0, 1).getDay() || 7;
var week = null;
if (yearFirstDay == 1) {
week = Math.ceil(days / yearFirstDay);
} else {
days -= (7 - yearFirstDay + 1);
week = Math.ceil(days / 7) + 1;
}
return week;
}
function getDatabaseFormatter(dateinf) {
if ("object" === typeof dateinf) {
var y = dateinf.getFullYear();
var m = dateinf.getMonth() + 1;
var d = dateinf.getDate();
return y.toString() + (m < 10 ? ('0' + m) : m).toString() + (d < 10 ? ('0' + d) : d).toString();
}
return dateinf;
}
function getDaysBetween (first, second) {
// Copy date parts of the timestamps, discarding the time parts.
var one = new Date(first.getYear(), first.getMonth(), first.getDate());
var two = new Date(second.getYear(), second.getMonth(), second.getDate());
// Do the math.
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = two.getTime() - one.getTime();
var days = millisBetween / millisecondsPerDay;
// Round down.
return Math.floor(days);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment