JavaScript Date对象详解和项目需求

来源:互联网 发布:类中静态变量和常量php 编辑:程序博客网 时间:2024/06/06 03:42

时间:2017年3月24日16:34:50

    作为初级工程师,开始需要学习的是业务流程和开发流程,随着这些经验的积累,对业务和开发已经熟悉的情况下,就是需要解决实际问题。实际项目中,需要解决的问题非常多,因此,将Date对象独立出来做记录。

    Date对象主要用于处理日期和时间:

1、创建Date对象

var date = new Date();

var date = new Date(milliseconds);

var date = new Date('Fri Mar 24 2017 16:42:54 GMT+0800 (中国标准时间)');

var date = new Date(year,month,day,hours,minutes,seconds,milliseconds);

2、Date对象实例化

var date = new Date();

console.log(date);//object类型的输出 > Fri Mar 24 2017 16:42:54 GMT+0800 (中国标准时间)

console.log(date.timeString());//16:46:19 GMT+0800 (中国标准时间)

console.log(date.String());//Fri Mar 24 2017 16:46:19 GMT+0800 (中国标准时间)

console.log(date.toLocaleString());//2017/3/24 下午4:46:19

console.log(date.toLocaleDateString());//2017/3/24

console.log(date.toLocaleTimeString());//下午4:46:19

console.log(date.toTimeString());//16:46:19 GMT+0800 (中国标准时间)

console.log(date.toJSON());//2017-03-24T08:46:19.944Z

console.log(date.toISOString());//2017-03-24T09:07:43.633Z

console.log(date.toDateString());//Fri Mar 24 2017


console.log(date.getDate());//一个月中的某一天

console.log(date.getDay());//一周中的某一天 0周日 1周一 ... 6周六

console.log(date.getFullYear());//四位数年份

console.log(date.getHours());//小时

console.log(date.getMilliseconds());//毫秒数

console.log(date.getMinutes());//

console.log(date.getMonth());//月份 0-11

console.log(date.Seconds());//


console.log(date.valueOf());//返回1970.1.1至今的毫秒数 > 1490344974156

console.log(date.getTime());//返回1970.1.1至今的毫秒数


3、创建指定日期的Date对象:

new Date().setTime(milliseconds) 等价于 new Date(milliseconds)

4、项目需求

    浏览器固定位置需要显示格式为:2017年3月18日-2017年3月24日,这个时间段指当天日期的一个周时间段。如果当天是周六或周日,则该时间段为本周六到下周五的时间段;如果当天是周一到周五任意一天,则该时间段为上周六到本周五的时间段。源码如下:

var date = new Date();
//date.setTime(1483341827500);//测试日期 ||  new Date(1483341827500)
var timeStamp = date.getTime();//当前时间戳
var weekDay = date.getDay();//星期日 0 星期一 1 ... 星期六 6
var saturdayTime,fridayTime,sat,fri,satDate,friDate;  
if(weekDay == 0){
saturdayTime= timeStamp - 1000*60*60*24;
fridayTime= timeStamp + 1000*60*60*24*5;
}else if(weekDay == 6){
saturdayTime= date.getTime();
fridayTime= timeStamp + 1000*60*60*24*6;
}else if(weekDay == 5){
saturdayTime= timeStamp - 1000*60*60*24*6;
fridayTime= date.getTime();
}else{
saturdayTime= timeStamp - 1000*60*60*24*(weekDay+1);
fridayTime= timeStamp + 1000*60*60*24*(5-weekDay);
}
satDate = new Date(saturdayTime).toLocaleDateString();//2017/3/18
friDate = new Date(fridayTime).toLocaleDateString();//2017/3/24
sat = (satDate.split('/'))[2];//2017/3/18 > ["2017", "3", "18"] > 18
fri = (friDate.split('/'))[2];
var displayTime = (satDate.split('/'))[0] + '年' + (satDate.split('/'))[1] +'月'+ sat +'日-' +(friDate.split('/'))[0] + '年' + (friDate.split('/'))[1] +'月'+ fri +'日';

0 0