好程序员web前端教程分享Date对象

182 阅读3分钟

好程序员web前端教程分享Date对象,什么是Date对象一个内置对象Date:

类型使用自 UTC(Coordinated Universal Time,国际协调时间)1970 年 1 月 1 日午夜(零时)开始经过的毫秒数来保存日期。Date 类型保存的日期能够精确到 1970 年 1 月 1日之前或之后的 285616 年。


Date对象怎么用那?

首先你要获得Date对象


得到微-信;

var d=new Date( );


在生成日期对象的时候,不传递任何参数默认返回当前时间;


var d=new Date( '2015/12/2');



在传入参数的情况下,获得的是传入的时间;


注:这个参数是字符串形式。


一些方法:


1.d.getFullYear() 获取当前的年份。|| d.setFullYear(2012) 返回1970年1月1日到设定时间毫秒数;


2.d.getMonth() 获取当前的月份(注:一个小BUG,当前的月份从0开始)||d.setMonth(9)返回1970年1月1日到当前年份的设定月份的毫秒数;


3.d.getDate()获取当前的日期 ||d.setDate() 同上;


4. getHours() 获取时

getMinutes() 获取分钟

getSeconds() 获取秒


各个机器获取的时间不同,因为该方法返回的是本机的时间;并不是国际标准时间;


5.日期的修改;

Date.parse("2015-08-24");获取1970年到设定时间的毫秒数;


d.getTime();获取1970年到当前时间的毫秒数;


d.setTime()

new Date(time)

创建一个日期对象,并指定时间 可以指定毫秒数

或者修改time属性, var d = new Date(); d.setTime(56521211021);


案例:


1.将日期格式化

<!doctype html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

</head>

<body>

</body>

<script>

function geshihua() {

var d = new Date();

var year = d.getFullYear();

var Month = d.getMonth() + 1;

var day = d.getDate();

var str = '当前时间是:' + year + '年' + Month + '月' + day + '日'

document.write(str);

}

geshihua()

</script>

</html>

  1. 获取某个月的天数:

<!doctype html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

<script>

function days(year, month) {

var str = year + '/' + month + '/1';

var d = new Date(str);

var Month = d.getMonth();

var MonthMin = d.setMonth(Month);

var MonthMin2 = d.setMonth(Month + 1);

var MonthDay = MonthMin2 - MonthMin

alert(MonthDay / 24 / 60 / 60 / 1000)

}

days('2014', '2')

</script>

</head>

<body>

</body>

</html>

  1. .计算日期差值

<!doctype html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

<style>

.btn{

background:none;

border: 1px solid #b6b6b6;

display: block;

height: 40px;

margin: 40px auto;

}

</style>

</head>

<body>

<div id="div1">

<input type="text" placeholder='起始年份'>

<input type="text" placeholder='起始月份'>

<input type="text" placeholder='起始日'>||

<input type="text" placeholder='终止年份'>

<input type="text" placeholder='终止月份'>

<input type="text" placeholder='终止日'>

</div>

<input type="button" value='计算日期差距' class="btn" onclick='jisuanriqi()'>

</body>

<script>

function jisuanriqi() {

var oDiv = document.getElementById('div1');

var aInput = oDiv.getElementsByTagName('input');

var qishiArr = [];

var zhongzhiArr = [];

for (var i = 0; i < aInput.length; i++) {

if (i < 3) {

qishiArr[i] = aInput[i].value;

} else {

zhongzhiArr[i] = aInput[i].value;

}

}

var str1 = qishiArr.join('/');

var str2 = zhongzhiArr.join('/');

var d1 = new Date(str1);

var d2 = new Date(str2);

alert(d1 + ":" + d2)

var days = Math.abs(d1.getTime() - d2.getTime()) / 1000 / 24 / 60 / 60;

alert(days)

}

</script>

</html>