Created
July 6, 2018 12:23
-
-
Save flxxyz/c15bde85fdfa5c001c9274eb5f401a67 to your computer and use it in GitHub Desktop.
javascript简易时间处理类
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var w = require('./with.js'); | |
const serveTime = '2017-01-01 00:00:00'; | |
setInterval(()=> { | |
console.log(w.serve(serveTime)); | |
}, 1000); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 时间常量 | |
const daySecond = 24 * 3600 * 1000; // 一天的秒数 | |
const hourSecond = 3600 * 1000; // 一小时的秒数 | |
const second = 60 * 1000; // 一分钟的秒数 | |
var time = {} | |
/** | |
* 格式化时间,以年月日时分秒输出 | |
* param Date date | |
* return string | |
*/ | |
time.YmdHms = (date) => { | |
let t = date ? new Date(date) : new Date; | |
with (t) return [ | |
getFullYear(), '年', | |
('0' + (getMonth() + 1)), '月', | |
('0' + getDate()).slice(-2), '日 ', | |
('0' + getHours()).slice(-2), ':', | |
('0' + getMinutes()).slice(-2), ':', | |
('0' + getSeconds()).slice(-2) | |
].join(''); | |
} | |
/** | |
* 格式化时间,以年月日输出 | |
* param Date date | |
* return string | |
*/ | |
time.Ymd = (date) => { | |
let t = date ? new Date(date) : new Date; | |
with (t) return [ | |
getFullYear(), '年', | |
('0' + (getMonth() + 1)), '月', | |
('0' + getDate()).slice(-2), '日' | |
].join(''); | |
} | |
/** | |
* 倒计时 | |
* param Date date | |
* return string | |
*/ | |
time.serve = (date) => { | |
with (Math) { | |
var initTime = new Date(date); // 启动时间 | |
var nowTime = new Date(); // 当前时间 | |
let diffTime = nowTime.getTime() - initTime.getTime(); // 时间的秒数差 | |
let leave1 = diffTime % daySecond; // 剩下小时的秒数 | |
let leave2 = leave1 % hourSecond; // 剩下分钟的秒数 | |
let leave3 = leave2 % (60 * 1000); //剩下的秒数 | |
var hours = Math.floor(leave1 / (3600 * 1000)); | |
return [ | |
floor(diffTime / daySecond), '天', | |
floor(leave1 / hourSecond), '小时', | |
floor(leave2 / second), '分', | |
floor(leave3 / 1000), '秒' | |
].join(''); | |
} | |
} | |
module.exports = time; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment