Skip to content

Instantly share code, notes, and snippets.

@vace
Last active January 29, 2018 05:39
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 vace/85096d2f2fdbe835ddc635afded5a338 to your computer and use it in GitHub Desktop.
Save vace/85096d2f2fdbe835ddc635afded5a338 to your computer and use it in GitHub Desktop.
javascript function
const REPLACE_REGEX = /(Y|M|D|H|I|S|T)/ig
export function timeFormat(unixTime, format = 'Y-M-D H:i:s') {
var time = new Date(unixTime * 1000)
var conf = {
Y: time.getFullYear(),
M: pad(time.getMonth() + 1), //月份
D: pad(time.getDate()), //日
H: pad(time.getHours()), //小时
I: pad(time.getMinutes()), //分
S: pad(time.getSeconds()), //秒
T: time.getTime()
}
return format.replace(REPLACE_REGEX, key => conf[key.toUpperCase()])
}
function pad(num){
return num > 10 ? num : ('0' + num)
}
/* eslint-disable */
var indexMapZh = '秒_分钟_小时_天_周_月_年'.split('_')
// build-in locales: en & zh_CN
var locales = {
'zh_CN': function (number, index) {
if (index === 0) return ['刚刚', '片刻后']
var unit = indexMapZh[parseInt(index / 2)]
return [number + unit + '前', number + unit + '后']
}
}
// second, minute, hour, day, week, month, year(365 days)
var SEC_ARRAY = [60, 60, 24, 7, 365 / 7 / 12, 12]
var SEC_ARRAY_LEN = 6
// format Date / string / timestamp to Date instance.
function toDate (input) {
if (input instanceof Date) return input
if (!isNaN(input)) return new Date(toInt(input))
if (/^\d+$/.test(input)) return new Date(toInt(input))
input = (input || '').trim().replace(/\.\d+/, '') // remove milliseconds
.replace(/-/, '/').replace(/-/, '/')
.replace(/(\d)T(\d)/, '$1 $2').replace(/Z/, ' UTC') // 2017-2-5T3:57:52Z -> 2017-2-5 3:57:52UTC
.replace(/([\+\-]\d\d)\:?(\d\d)/, ' $1$2') // -04:00 -> -0400
return new Date(input)
}
// change f into int, remove Decimal. just for code compression
function toInt (f) {
return parseInt(f)
}
// format the diff second to *** time ago, with setting locale
function formatDiff (diff) {
var locale = 'zh_CN'
var i = 0
var agoin = diff < 0 ? 1 : 0 // timein or timeago
diff = Math.abs(diff)
for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) {
diff /= SEC_ARRAY[i]
}
diff = toInt(diff)
i *= 2
if (diff > (i === 0 ? 9 : 1)) i += 1
return locales[locale](diff, i)[agoin].replace('%s', diff);
}
// calculate the diff second between date to be formated an now date.
export function timeago (unix_time) {
let diff = Date.now() / 1000 - unix_time
return formatDiff(diff)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment