formatTime.js 1004 B

12345678910111213141516171819202122232425262728293031323334
  1. /**
  2. * @desc 格式化时间戳为年月日时分秒
  3. * @param {Number,Date} date
  4. * @param {String} fmt
  5. * @return {String}
  6. */
  7. function isDate(o) {
  8. return Object.prototype.toString.call(o) === '[object Date]';
  9. }
  10. var formatTime = function formatTime(date) {
  11. var fmt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'yyyy-MM-dd hh:mm:ss';
  12. if (isDate(date) === false) {
  13. date = new Date(+date);
  14. }
  15. var o = {
  16. 'M+': date.getMonth() + 1,
  17. 'd+': date.getDate(),
  18. 'h+': date.getHours(),
  19. 'm+': date.getMinutes(),
  20. 's+': date.getSeconds(),
  21. 'q+': Math.floor((date.getMonth() + 3) / 3),
  22. 'S': date.getMilliseconds()
  23. };
  24. if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  25. for (var k in o) {
  26. if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
  27. }
  28. return fmt;
  29. };
  30. module.exports = formatTime;