js處理時間(一)

最近正好閒下來了!整理了一下時間處理的方法,都是自己寫的哈!!

本篇封裝:

(1) js取得2016-08-11 19:46:01格式的時間

(2) js取得本週第一天/最後一天

(3) js取得本月第一天/最後一天

    <script type="text/javascript">
 
/* 輸出2016-08-11 19:46:01的格式 */
  var today = new Date()
  //昨天:先算出昨天的日期,用setDate方法把今天日期減1
  today.setDate(today.getDate() - 1)
  console.log(today)
  //向 1970/01/01 添加 77771564221 毫秒
  //today.setTime(77771564221)
  //設置爲月初第一天
  today.setDate(1)
 
  year = today.getFullYear()
  month = today.getMonth().toString().length == 1?'0'+(today.getMonth()+1):today.getMonth()+1
  dateString = today.getDate()<=9?'0'+today.getDate():today.getDate()
  hour = today.getHours()<=9?'0'+today.getHours():today.getHours()
  min = today.getMinutes()<=9?'0'+today.getMinutes():today.getMinutes()
  sec = today.getSeconds()<=9?'0'+today.getSeconds():today.getSeconds()
 
  dateFormat = year+'-'+month+'-'+dateString + ' ' + hour + ':' + min + ':' + sec
  console.log(dateFormat)
 
    /* 月份 星期第一天測試
  var today = new Date(), msg = [];
  today.setDate(12)
  var todayDate = today.getDate()
  var todayWeekDay = today.getDay()
    */
 
    /*week開始的第一天
    today.setDate(todayDate-todayWeekDay)   //此處的today是當週的第一天
    weekFirstDay = today.getFullYear().toString() +"-"+ (today.getMonth()+1) +"-"+ today.getDate()
    weekFirstDate = today.getDate() //獲取當週第一天的日期
    alert(weekFirstDay)
 
 
    today.setDate(weekFirstDate+6)  //此處的today是當週第六天 即最後一天j
    weekLastDay = today.getFullYear().toString() +"-"+ (today.getMonth()+1) +"-"+ today.getDate()
    alert(weekLastDay)
    */
 
    /* month 第一天
    today.setDate(1) //此處的today是當月的第一天
    monthFirstDay = today.getFullYear().toString() +"-"+ (today.getMonth()+1) +"-"+ (today.getDate())
    alert(monthFirstDay)
 
    today.setMonth(today.getMonth()+1) //此處的today是下個月的第一天
    today.setDate(0) //此處的today是當月的最後一天
    monthLastDay = today.getFullYear().toString() +"-"+ (today.getMonth()+1) +"-"+ (today.getDate())
    alert(monthLastDay)
    */
    </script>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章