인간 친화적 인 상대 날짜 형식을위한 자바 스크립트 라이브러리
사람에게 친숙한 형식으로 현재 날짜를 기준으로 일부 날짜를 표시하고 싶습니다.
인간 친화적 인 상대 날짜의 예 :
- 10 초 전
- 지금부터 20 분
- 1 일 전
- 5 주전
- 2 달전
기본적으로 가장 높은 등급을 충실히 보존합니다 (그리고 선호에 따라 해당 단위 중 2 개를 통과 할 때만 단위 이동-1 개월 대신 5 주).
통제력이 약하고 다음과 같은 친근한 날짜를 가진 도서관에서 살 수는 있지만
- 어제
- 내일
- 지난주
- 몇 분 전
- 몇 시간 안에
이것에 대한 인기있는 도서관이 있습니까?
이 답변을 작성했기 때문에 사용 가능한 잘 알려진 라이브러리는 moment.js 입니다.
있습니다 가능한 라이브러리는 있지만, 스스로를 구현하기 간단하다. 몇 가지 조건을 사용하십시오.
비교하려는 시간에 대해 date
인스턴스화 된 Date
객체라고 가정합니다 .
// Make a fuzzy time
var delta = Math.round((+new Date - date) / 1000);
var minute = 60,
hour = minute * 60,
day = hour * 24,
week = day * 7;
var fuzzy;
if (delta < 30) {
fuzzy = 'just then.';
} else if (delta < minute) {
fuzzy = delta + ' seconds ago.';
} else if (delta < 2 * minute) {
fuzzy = 'a minute ago.'
} else if (delta < hour) {
fuzzy = Math.floor(delta / minute) + ' minutes ago.';
} else if (Math.floor(delta / hour) == 1) {
fuzzy = '1 hour ago.'
} else if (delta < day) {
fuzzy = Math.floor(delta / hour) + ' hours ago.';
} else if (delta < day * 2) {
fuzzy = 'yesterday';
}
미래 날짜를 처리하려면이를 조정해야합니다.
이 작업을 수행하는 날짜 라이브러리 인 moment.js를 작성 했습니다. 약
5KB (2011)
52KB (2019)이며 브라우저와 Node.js에서 작동합니다. 또한 JavaScript를위한 가장 인기 있고 유명한 날짜 라이브러리 일 것입니다.
timeago, 형식화, 구문 분석, 쿼리, 조작, i18n 등을 지원합니다.
과거 날짜에 대한 Timeago (상대 시간)는 moment().fromNow()
. 예를 들어 2019 년 1 월 1 일을 timeago 형식으로 표시하려면 :
let date = moment("2019-01-01", "YYYY-MM-DD");
console.log(date.fromNow());
<script src="https://momentjs.com/downloads/moment.min.js"></script>
The timeago strings are customizable with moment.updateLocale()
, so you can change them how you see fit.
The cutoffs are not what the question requests ("5 weeks" vs. "1 month"), but it is documented as to which strings are used for what time range.
sugar.js has great date formatting functions.
Not only that, it also provides common general purpose functions like string formatting, number formatting, etc. that are convenient to use.
Here's something from the John Resig - http://ejohn.org/blog/javascript-pretty-date/
EDIT (6/27/2014): Following up on the comment from Sumurai8 - though the linked page still works, here is the excerpt for the pretty.js
linked to from the article above:
pretty.js
/*
* JavaScript Pretty Date
* Copyright (c) 2011 John Resig (ejohn.org)
* Licensed under the MIT and GPL licenses.
*/
// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time) {
var date = new Date((time || "").replace(/-/g, "/").replace(/[TZ]/g, " ")),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);
if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) return;
return day_diff == 0 && (
diff < 60 && "just now" || diff < 120 && "1 minute ago" || diff < 3600 && Math.floor(diff / 60) + " minutes ago" || diff < 7200 && "1 hour ago" || diff < 86400 && Math.floor(diff / 3600) + " hours ago") || day_diff == 1 && "Yesterday" || day_diff < 7 && day_diff + " days ago" || day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago";
}
// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if (typeof jQuery != "undefined") jQuery.fn.prettyDate = function() {
return this.each(function() {
var date = prettyDate(this.title);
if (date) jQuery(this).text(date);
});
};
Usage:
prettyDate("2008-01-28T20:24:17Z") // => "2 hours ago"
prettyDate("2008-01-27T22:24:17Z") // => "Yesterday"
prettyDate("2008-01-26T22:24:17Z") // => "2 days ago"
prettyDate("2008-01-14T22:24:17Z") // => "2 weeks ago"
prettyDate("2007-12-15T22:24:17Z") // => undefined
Excerpt from the article on usage:
Example Usage
In the following examples I make all the anchors on the site, that have a title with a date in it, have a pretty date as their inner text. Additionally, I continue to update the links every 5 seconds after the page has loaded.
With JavaScript:
function prettyLinks(){
var links = document.getElementsByTagName("a");
for ( var i = 0; i < links.length; i++ )
if ( links[i].title ) {
var date = prettyDate(links[i].title);
if ( date )
links[i].innerHTML = date;
}
}
prettyLinks();
setInterval(prettyLinks, 5000);
With jQuery:
$("a").prettyDate();
setInterval(function(){ $("a").prettyDate(); }, 5000);
Faiz: Made some changes to the original code, bug fixes and improvements.
function prettyDate(time) {
var date = new Date((time || "").replace(/-/g, "/").replace(/[TZ]/g, " ")),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);
var year = date.getFullYear(),
month = date.getMonth()+1,
day = date.getDate();
if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31)
return (
year.toString()+'-'
+((month<10) ? '0'+month.toString() : month.toString())+'-'
+((day<10) ? '0'+day.toString() : day.toString())
);
var r =
(
(
day_diff == 0 &&
(
(diff < 60 && "just now")
|| (diff < 120 && "1 minute ago")
|| (diff < 3600 && Math.floor(diff / 60) + " minutes ago")
|| (diff < 7200 && "1 hour ago")
|| (diff < 86400 && Math.floor(diff / 3600) + " hours ago")
)
)
|| (day_diff == 1 && "Yesterday")
|| (day_diff < 7 && day_diff + " days ago")
|| (day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago")
);
return r;
}
This js script is very nice. All you have to do is to execute it. All <time>
tags will be changed to relative dates and updated every few minutes, so the relative time will always be up to date.
here an example of sugar vs moment: for a calendar that displays weeks, I needed the last monday value:
moment.js
var m = moment().subtract("days", 1).sod().day(1) // returns a "moment"
sugar.js
var d = Date.past("monday") // returns a js Date object
I much prefer sugar and after some months with moment.js now switch to sugar.js. it is clearer and integrates nicely with Javascripts' Date class.
OP cases are covered by both libs, for sugar.js see http://sugarjs.com/dates
Sounds like you could use http://www.datejs.com/
They have an example on the main page that does exactly what you're describing!
EDIT: Actually, I think I reversed your question in my head. In any case, I think you could check it out as it's a really great library anyway!
EDIT x2: I'm going to echo what the others have said http://momentjs.com/ is probably the best choice available right now.
EDIT x3: I haven't used date.js in over a year. I'm exclusively using momentjs for all my date related needs.
'program tip' 카테고리의 다른 글
async componentDidMount () 사용이 좋은가요? (0) | 2020.09.10 |
---|---|
빈 배열 항목을 건너 뛰면서 배열을 내파하려면 어떻게해야합니까? (0) | 2020.09.09 |
Android 용 로컬 이미지 캐싱 솔루션 : Square Picasso, Universal Image Loader, Glide, Fresco? (0) | 2020.09.09 |
Oracle Virtual Box에서 이미지를 시작할 때 VERR_VMX_MSR_VMXON_DISABLED (0) | 2020.09.09 |
userID를 매개 변수로 전달하지 않고 ApiController 작업 내에서 현재 사용자 가져 오기 (0) | 2020.09.09 |