time.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. function formatActivity(seconds) {
  2. var h = parseInt(seconds / 3600) //小时
  3. var m = parseInt((seconds / 60) % 60) //分钟
  4. var s = parseInt(seconds % 60) //当前的秒
  5. h = h < 10 ? '0' + h : h
  6. m = m < 10 ? '0' + m : m
  7. s = s < 10 ? '0' + s : s
  8. return h + ':' + m + ':' + s
  9. }
  10. /**
  11. * 时间戳格式化函数
  12. * @param {string} format 格式 Y-m-d H:i:s
  13. * @param {int} timestamp 要格式化的时间 默认为当前时间
  14. * @return {string} 格式化的时间字符串
  15. */
  16. function timestampToDate(timestamp, format) {
  17. format = format || 'Y-m-d'
  18. let zero = function (value) {
  19. if (value < 10) {
  20. return '0' + value
  21. }
  22. return value
  23. }
  24. let myDate = timestamp ? new Date(timestamp * 1000) : new Date()
  25. let year = myDate.getFullYear()
  26. let month = zero(myDate.getMonth() + 1)
  27. let day = zero(myDate.getDate())
  28. let hour = zero(myDate.getHours())
  29. let minite = zero(myDate.getMinutes())
  30. let second = zero(myDate.getSeconds())
  31. return format.replace(/Y|m|d|H|i|s/gi, function (matches) {
  32. return {
  33. Y: year,
  34. m: month,
  35. d: day,
  36. H: hour,
  37. i: minite,
  38. s: second
  39. }[matches]
  40. })
  41. }
  42. module.exports = {
  43. formatActivity: formatActivity,
  44. timestampToDate: timestampToDate
  45. }