Skip to content

Instantly share code, notes, and snippets.

@redblue9771
Created July 12, 2019 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redblue9771/4e736da32120b263be2fe63160a581d9 to your computer and use it in GitHub Desktop.
Save redblue9771/4e736da32120b263be2fe63160a581d9 to your computer and use it in GitHub Desktop.
JavaScript中一些时间功能的实现 - 格式化时间戳(yy/mm/dd hh:MM)
/**
* 格式化时间戳 格式:yy/mm/dd hh:MM
* @param time 时间戳
* @returns {string} yy/mm/dd hh:MM
*/
function formatTime(time) {
var date = new Date(time);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var days = date.getDate();
var hours = date.getHours();
var mins = date.getMinutes();
return year + '/' + transFormat(month) + '/' + transFormat(days) + ' ' + transFormat(hours) + ':' + transFormat(mins);
}
/**
* 补齐一位数字前面的0,使得输出美观
* @param value
* @returns {string}
*/
function transFormat(value) {
return ('0' + value).slice(-2);
}
document.write(formatTime(1509019200000));
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/**
* 格式化时间戳(f带字符串的) 格式:yy/mm/dd hh:MM
* @param time 时间戳
* @returns {string} yy/mm/dd hh:MM
*/
function formatTime(time,value) {
var date = new Date(time);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var days = date.getDate();
var hours = date.getHours();
var mins = date.getMinutes();
return value.replace(/(yy)+/i,year).replace(/mm/,transFormat(month)).replace(/dd/i,transFormat(days)).replace(/hh/i,transFormat(hours)).replace(/MM/,transFormat(mins));
}
document.write(formatTime(1509019200000,"yyyy/mm/dd hh:MM"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment