js 获取是否为闰年,以及各月的天数 & isLeapYear
js 获取是否为闰年,以及各月的天数
calendar utils
isLeapYear
const isLeapYear = (year) => {
return (year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0);
}
const year = new Date().getFullYear()
isLeapYear(year);
getMonthDays
const getMonthDays = (timestamp) => {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = date.getMonth() + 1;
let days = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 2:
if(isLeapYear(year)) {
days = 29;
} else {
days = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
default:
break;
}
return days;
}
function isLeapYear(year) {
// 如果year年2月没有29则自动进一变为3月1日
var date = new Date(year, 1, 29)
return date.getDate() === 29
}
isLeapYear(2000) // true
isLeapYear(2001) // false
// 将时间设置为这个月的下一月的第一天,然后回拨一秒
function monthDay(year, month) {
var date = new Date(year, month, 1, 0, 0, 0)
var yesterDay = new Date(date - 1000)
return yesterDay.getDate()
}
monthDay(2017, 2) // 28
monthDay(2017, 12) // 31
isToday
const isToday = (timestamp = ``) => {
return new Date(timestamp).toLocaleDateString() === new Date().toLocaleDateString();
}
format today
const autoGetToday = (time = ``, debug = false) => {
let log = console.log;
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
if (debug) {
log(year);
log(month);
log(day);
}
let today = `${year}/${month}/${day} ${time}`;
if (debug) {
log(`today =`, today);
}
return today;
};
refs
https://www.cnblogs.com/xgqfrms/p/12661145.html
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/12667959.html
未经授权禁止转载,违者必究!