您的位置:首页 > Web前端 > JavaScript

js处理时间(一)

2016-09-09 16:05 330 查看
最近正好闲下来了!整理了一下时间处理的方法,都是自己写的哈!!

本篇封装:

(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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: