博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

js的new Date()日期的使用

Posted on 2017-10-13 14:40  人生梦想起飞  阅读(4036)  评论(0编辑  收藏  举报
<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>