前端new Date()日期的使用

突发奇想,在Date的使用方式上有短板,遇到指定年份的时间格式转换时一筹莫展,特此码下此篇

亮眼,在年轮里取得我想要的功能函数
亮眼,在年轮里取得我想要的功能函数

 <script type="text/javascript">

//js获取某个月的天数
function days(year,month){
    var dayCount;
    now = new Date(year,month, 0);
    dayCount = now.getDate();
    return dayCount;
}
console.log(days(2017,10))
//js计算系统当前日期是星期几的几种方法
console.log(new Date().getDay())
console.log(new Date(2017,7,13).getDay())
 
//格式化日期:yyyy-MM-dd
function formatDate(date) {
var myyear = date.getFullYear();
var mymonth = date.getMonth()+1;
var myweekday = date.getDate();
 
if(mymonth < 10){
mymonth = "0" + mymonth;
}
if(myweekday < 10){
myweekday = "0" + myweekday;
}
return (myyear+"-"+mymonth + "-" + myweekday);
}
//获取本周第一天的日期
function showWeekFirstDay(){    
    var now = new Date(2017,0,1);    
    var nowTime = now.getTime() ;
    var day = now.getDay();
    var oneDayTime = 24*60*60*1000 ;
    //显示周一
    if(day == 0){
      day = 7;
    }
    var MondayTime = nowTime - (day-1)*oneDayTime ;
    return formatDate(new Date(MondayTime));    
}
console.log(showWeekFirstDay())
//获得本周的结束日期
function getWeekEndDate() {
    var now = new Date(2017,8,5);    
    var nowTime = now.getTime() ;
    var day = now.getDay();
    var oneDayTime = 24*60*60*1000 ;
    //显示周一
    if(day == 0){
      day = 7;
    }
    var SundayTime =  nowTime + (7-day)*oneDayTime ;
    return formatDate(new Date(SundayTime));
}
console.log(getWeekEndDate())
//获取本月第一天
function showMonthFirstDay(){    
    var Nowdate=new Date(2017,1);    
    var MonthFirstDay=new Date(Nowdate.getFullYear(),Nowdate.getMonth(),1);    
    M=Number(MonthFirstDay.getMonth())+1    
    return MonthFirstDay.getFullYear()+"-"+M+"-"+MonthFirstDay.getDate();    
}
console.log(showMonthFirstDay())
//获取本月的最后一天
function showMonthLastDay(){    
    var Nowdate=new Date(2017,8);    
    var MonthNextFirstDay=new Date(Nowdate.getFullYear(),Nowdate.getMonth()+1,1);    
    var MonthLastDay=new Date(MonthNextFirstDay-86400000);    
    M=Number(MonthLastDay.getMonth())+1    
    return MonthLastDay.getFullYear()+"-"+M+"-"+MonthLastDay.getDate();    
}
console.log(showMonthLastDay())
</script>

原文链接:https://www.cnblogs.com/dearxinli/p/7661100.html

添加新评论