-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
98 lines (98 loc) · 2.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict';
var moment = require('moment');
var _ = require('lodash');
var template = require('./template');
/**
*
* @param time
* @param form
* @param language
* @returns {string}
*/
function format(time, form, language) {
if (form == 'weibo') {
return format(time, template.weibo, 'zh-cn');
} else if (form == 'weiboMobile') {
return format(time, template.weiboMobile, 'zh-cn');
} else if (form == 'wechat') {
return format(time, template.wechat, 'zh-cn');
} else {
var timeResult;
if (language) {
moment.locale(language);
}
var nowTime = moment().format("YYYY-MM-DD HH:mm:ss");
var now = moment(nowTime).unix();
var timeUnix = moment(time).unix();
var diff = now - timeUnix;
var result = form.map(function (condition) {
if (condition.limit && condition.above) {
if (diff < condition.limit && diff > condition.above) {
timeResult = formatTime(time, diff, condition.unit);
if (condition.leftString && condition.rightString) {
return condition.leftString + timeResult + condition.rightString;
} else if (condition.leftString) {
return condition.leftString + timeResult;
} else if (condition.rightString) {
return timeResult + condition.rightString;
} else {
return timeResult;
}
} else {
return 0;
}
} else {
if (diff < condition.limit || diff > condition.above) {
timeResult = formatTime(time, diff, condition.unit);
if (condition.leftString && condition.rightString) {
return condition.leftString + timeResult + condition.rightString;
} else if (condition.leftString) {
return condition.leftString + timeResult;
} else if (condition.rightString) {
return timeResult + condition.rightString;
} else {
return timeResult;
}
} else {
return 0;
}
}
});
var resultTime = _.compact(result).join('');
return resultTime;
}
}
/**
*
* @param time
* @param diff
* @param unit
* @returns {*}
*/
var formatTime = function (time, diff, unit) {
var result;
switch (unit) {
case undefined :
result = '';
break;
case 'second':
result = diff;
break;
case 'minute':
result = _.floor(diff / 60);
break;
case 'hour':
result = _.floor(diff / (60 * 60));
break;
case 'date':
result = _.floor(diff / (60 * 60 * 24));
break;
case 'week':
result = _.floor(diff / (60 * 60 * 24 * 7));
break;
default:
result = moment(time).format(unit);
}
return result;
};
module.exports = format;