Skip to content
This repository has been archived by the owner on Nov 15, 2018. It is now read-only.

Commit

Permalink
fix: (#204) 按需求格式化时间字符串(全局有效)
Browse files Browse the repository at this point in the history
  • Loading branch information
mutoe committed Jun 19, 2018
1 parent 6b4527d commit f930f28
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
"register-service-worker": "^1.0.0",
"strophe.js": "^1.2.14",
"swiper": "^4.1.6",
"timeago.js": "^3.0.2",
"underscore": "^1.8.3",
"vue": "^2.5.16",
"vue-router": "^3.0.1",
Expand All @@ -51,5 +50,7 @@
"not ie <= 8",
"Safari 6"
],
"eslintIgnore": ["dist/*"]
"eslintIgnore": [
"dist/*"
]
}
16 changes: 13 additions & 3 deletions src/filters.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import timeago from "timeago.js";
import plueMessageBundle from "plus-message-bundle";

/**
Expand Down Expand Up @@ -61,6 +60,7 @@ export function formatDate(date, fmt = "yyyy/MM/dd hh:mm") {

/**
* 时间转提示
* 用于显示在我的动态时间轴
* @author jsonleex <[email protected]>
* @param {String} str
* @return {String}
Expand All @@ -87,12 +87,22 @@ export const time2txt = str => {
// 格林威治时间和本地时间之间的时差 (单位:毫秒)
export const timeOffset = new Date().getTimezoneOffset() * 60 * 1000;

export const dateFormat = timeago(null, "zh_CN");
export const time2tips = date => {
const time =
new Date(typeof date === "string" ? date.replace(/-/g, "/") : date) -
timeOffset;
return dateFormat.format(time - new Date() > 0 ? new Date() : time);
const offset = (new Date().getTime() - time) / 1000;
if (offset < 60) return "1分钟内";
if (offset < 3600) return `${~~(offset / 60)}分钟前`;
if (offset < 3600 * 24) return `${~~(offset / 3600)}小时前`;
// 根据 time 获取到 "16:57"
const timeStr = new Date(time).toTimeString().match(/^\d{2}:\d{2}/)[0];
if (offset < 3600 * 24 * 2) return `昨天 ${timeStr}`;
if (offset < 3600 * 24 * 9) return `${~~(offset / 3600 / 24)}天前 ${timeStr}`;
// 根据 time 获取到 "2018/6/19 16:57:39" 然后正则转化为 6-19 16:57
return new Date(time)
.toLocaleString("zh-CN", { hour12: false })
.replace(/^\d+\/(\d+)\/(\d+) (\d+:\d+):\d+$/, "$1-$2 $3");
};

/**
Expand Down

0 comments on commit f930f28

Please sign in to comment.