js内置对象-Date-时间戳

Date构造函数:可以创建日期和对象 用来处理日期和时间
1、创建时间对象:var date = new Date()=>当前时间=====构造函数传日期字符串指定具体的日期
2、格式化时间:data.tostring() 默认的时间格式,让日期以标准化的日期字符串格式输出
data.toLocaleString()当地的时间格式 本地化日期字符串格式输出
3、getFullYear(); 获取年 getMonth();获取月 getDay();获取星期 getDate();获取日期
getHours();获取小时 getMinutes();获取分钟 getSeconds();获取秒钟 getMilliseconds();获取毫秒

例题:

// 3. 日期格式的自定义, xx年xx月xx日 获取日期里面的各个组成部分
// 封装一个函数, 专门给小于 10 的数, 前面加上 0, 3 => "03"
function addZero( n ) {
if (n < 10) {
return '0' + n;
}
else {
return n;
}
}

var now = new Date(); // 当前时间

// 获取年 getFullYear
var year = now.getFullYear();

// 获取月 getMonth, 月从0开始, 范围0-11
var month = now.getMonth() + 1;
month = addZero(month);

// 获取日 getDate
// 获取一周中的第几天, getDay, 范围0-6, 0周日, 1周1
var day = now.getDate();

// 时 getHours
var hours = now.getHours();

// 分 getMinutes
var minutes = now.getMinutes();

// 秒 getSeconds
var seconds = now.getSeconds();
seconds = addZero(seconds);

// now.getMilliseconds 毫秒 0-1000

// console.log(year, month, day, hours, minutes, seconds);
var str = year + '年' + month + '月' + day + '日, ' + hours + '时' + minutes + '分' + seconds + '秒';
console.log(str);


4、时间戳:距离1970年1月1日0时0分0秒所过去的毫秒数
时间戳就是数字格式的日期,便于运算,一般用于求时间差
应用:1、用于统计一段代码的执行时间(性能优化)2、用于秒杀倒计时

例题:还有多久下课?

// 距离下课还有多久
var now = new Date(); // 当前时间
var future = new Date("2019-4-22 18:00:00");

var time = parseInt((future - now) / 1000); // 秒数

// 将秒数转换成 时 分 秒
// 时, 1小时 = 3600秒 4000 1小时多一点
var hours = parseInt(time / 3600);

// 分, 1分钟 = 60秒, 先求总的分钟数, 对60取余数, 因为满60的进位了
var minutes = parseInt(time / 60) % 60;

// 秒, 70秒 => 1分钟10秒, 超过60的都进位了
var seconds = time % 60;

// console.log(time);
// console.log(hours, minutes, seconds);
var str = "距离下课还有: " + hours + '时' + minutes + '分' + seconds + '秒';
document.write(str);

猜你喜欢

转载自www.cnblogs.com/hhmmpp/p/10992207.html