초 단위로 주어진 시간 간격을 사람이 읽을 수있는 형식으로 변환
초 단위로 주어진 시간을 사람이 읽을 수있는 형식으로 변환하기위한 코드 조각이 필요합니다. 함수는 숫자를 받고 다음과 같은 문자열을 출력해야합니다.
34 seconds
12 minutes
4 hours
5 days
4 months
1 year
형식이 필요하지 않으며 하드 코딩 된 형식이 사용됩니다.
function secondsToString(seconds)
{
var numyears = Math.floor(seconds / 31536000);
var numdays = Math.floor((seconds % 31536000) / 86400);
var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;
return numyears + " years " + numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";
}
Royi의 도움으로 시간 간격을 사람이 읽을 수있는 형식으로 출력하는 코드가 있습니다 .
function millisecondsToStr (milliseconds) {
// TIP: to find current time in milliseconds, use:
// var current_time_milliseconds = new Date().getTime();
function numberEnding (number) {
return (number > 1) ? 's' : '';
}
var temp = Math.floor(milliseconds / 1000);
var years = Math.floor(temp / 31536000);
if (years) {
return years + ' year' + numberEnding(years);
}
//TODO: Months! Maybe weeks?
var days = Math.floor((temp %= 31536000) / 86400);
if (days) {
return days + ' day' + numberEnding(days);
}
var hours = Math.floor((temp %= 86400) / 3600);
if (hours) {
return hours + ' hour' + numberEnding(hours);
}
var minutes = Math.floor((temp %= 3600) / 60);
if (minutes) {
return minutes + ' minute' + numberEnding(minutes);
}
var seconds = temp % 60;
if (seconds) {
return seconds + ' second' + numberEnding(seconds);
}
return 'less than a second'; //'just now' //or other string you like;
}
작업을 잘 수행하는 기존 자바 스크립트 라이브러리에 관심이 있다면 moment.js 를 확인하는 것이 좋습니다 .
더 구체적으로, 질문과 관련된 moment.js 부분은 durations 입니다.
다음은이를 활용하여 작업을 수행하는 방법에 대한 몇 가지 예입니다.
var duration = moment.duration(31536000);
// Using the built-in humanize function:
console.log(duration.humanize()); // Output: "9 hours"
console.log(duration.humanize(true)); // Output: "in 9 hours"
moment.js는 50 개 이상의 인간 언어를 기본적으로 지원하므로이 humanize()
방법을 사용하면 무료로 다국어 지원을받을 수 있습니다.
정확한 시간 정보를 표시하려면 정확히이 목적으로 생성 된 moment.js 용 moment-precise-range 플러그인 을 활용할 수 있습니다 .
console.log(moment.preciseDiff(0, 39240754000);
// Output: 1 year 2 months 30 days 5 hours 12 minutes 34 seconds
한 가지 주목할 점은 현재 moment.js는 duration 객체에 대해 주 / 일 (주 단위)을 지원하지 않는다는 것입니다.
도움이 되었기를 바랍니다!
@Royi의 응답에 따라 스윙을했습니다.
/**
* Translates seconds into human readable format of seconds, minutes, hours, days, and years
*
* @param {number} seconds The number of seconds to be processed
* @return {string} The phrase describing the the amount of time
*/
function forHumans ( seconds ) {
var levels = [
[Math.floor(seconds / 31536000), 'years'],
[Math.floor((seconds % 31536000) / 86400), 'days'],
[Math.floor(((seconds % 31536000) % 86400) / 3600), 'hours'],
[Math.floor((((seconds % 31536000) % 86400) % 3600) / 60), 'minutes'],
[(((seconds % 31536000) % 86400) % 3600) % 60, 'seconds'],
];
var returntext = '';
for (var i = 0, max = levels.length; i < max; i++) {
if ( levels[i][0] === 0 ) continue;
returntext += ' ' + levels[i][0] + ' ' + (levels[i][0] === 1 ? levels[i][1].substr(0, levels[i][1].length-1): levels[i][1]);
};
return returntext.trim();
}
내 좋은 점은 반복적 인 if
s 가 없으며 예를 들어 0 년 0 일 30 분 1 초 를 주지 않는다는 것 입니다.
예를 들면 :
forHumans(60)
출력 1 minute
forHumans(3600)
출력 1 hour
및 forHumans(13559879)
출력156 days 22 hours 37 minutes 59 seconds
다음을 시도하십시오.
seconds = ~~(milliseconds / 1000);
minutes = ~~(seconds / 60);
hours = ~~(minutes / 60);
days = ~~(hours / 24);
weeks = ~~(days / 7);
year = ~~(days / 365);
노트 :
- 보통 1 년은 365 일입니다. 윤년에는 366 일이 있으므로 이것이 문제인지 추가 확인이 필요합니다.
- 일광 절약과 유사한 문제. 어떤 날에는 23 시간이 있고 시간이 바뀌면 약 25 시간이 있습니다.
결론 : 이것은 무례하지만 작고 간단한 스 니펫입니다. :)
millisToTime = function(ms){
x = ms / 1000;
seconds = Math.round(x % 60);
x /= 60;
minutes = Math.round(x % 60);
x /= 60;
hours = Math.round(x % 24);
x /= 24;
days = Math.round(x);
return {"Days" : days, "Hours" : hours, "Minutes" : minutes, "Seconds" : seconds};
}
이것은 정수로 밀리 초가 걸리며 필요한 모든 정보를 포함하는 JSON 객체를 제공합니다.
훨씬 더 간단하고 읽기 쉽습니다.
milliseconds = 12345678;
mydate=new Date(milliseconds);
humandate=mydate.getUTCHours()+" hours, "+mydate.getUTCMinutes()+" minutes and "+mydate.getUTCSeconds()+" second(s)";
다음을 제공합니다.
"3 시간 25 분 45 초"
function millisecondsToString(milliseconds) {
var oneHour = 3600000;
var oneMinute = 60000;
var oneSecond = 1000;
var seconds = 0;
var minutes = 0;
var hours = 0;
var result;
if (milliseconds >= oneHour) {
hours = Math.floor(milliseconds / oneHour);
}
milliseconds = hours > 0 ? (milliseconds - hours * oneHour) : milliseconds;
if (milliseconds >= oneMinute) {
minutes = Math.floor(milliseconds / oneMinute);
}
milliseconds = minutes > 0 ? (milliseconds - minutes * oneMinute) : milliseconds;
if (milliseconds >= oneSecond) {
seconds = Math.floor(milliseconds / oneSecond);
}
milliseconds = seconds > 0 ? (milliseconds - seconds * oneSecond) : milliseconds;
if (hours > 0) {
result = (hours > 9 ? hours : "0" + hours) + ":";
} else {
result = "00:";
}
if (minutes > 0) {
result += (minutes > 9 ? minutes : "0" + minutes) + ":";
} else {
result += "00:";
}
if (seconds > 0) {
result += (seconds > 9 ? seconds : "0" + seconds) + ":";
} else {
result += "00:";
}
if (milliseconds > 0) {
result += (milliseconds > 9 ? milliseconds : "0" + milliseconds);
} else {
result += "00";
}
return result;
}
시간을 밀리 초 단위로 사람이 읽을 수있는 형식으로 변환합니다.
function timeConversion(millisec) {
var seconds = (millisec / 1000).toFixed(1);
var minutes = (millisec / (1000 * 60)).toFixed(1);
var hours = (millisec / (1000 * 60 * 60)).toFixed(1);
var days = (millisec / (1000 * 60 * 60 * 24)).toFixed(1);
if (seconds < 60) {
return seconds + " Sec";
} else if (minutes < 60) {
return minutes + " Min";
} else if (hours < 24) {
return hours + " Hrs";
} else {
return days + " Days"
}
}
논리에 대해 @Dan / @ Royi에게 감사드립니다. 그러나 구현은 XX 일, XX 분과 같은 시간 문자열을 빌드하지 않습니다. 나는 그들의 코드를 약간 조정했습니다.
function millisecondsToStr( milliseconds ) {
let temp = milliseconds / 1000;
const years = Math.floor( temp / 31536000 ),
days = Math.floor( ( temp %= 31536000 ) / 86400 ),
hours = Math.floor( ( temp %= 86400 ) / 3600 ),
minutes = Math.floor( ( temp %= 3600 ) / 60 ),
seconds = temp % 60;
if ( days || hours || seconds || minutes ) {
return ( years ? years + "y " : "" ) +
( days ? days + "d " : "" ) +
( hours ? hours + "h " : "" ) +
( minutes ? minutes + "m " : "" ) +
Number.parseFloat( seconds ).toFixed( 2 ) + "s";
}
return "< 1s";
}
실행하면
console.log("=", millisecondsToStr( 1540545689739 - 1540545684368 ));
console.log("=", millisecondsToStr( 351338536000 ));
결과는 다음과 같습니다.
= 5.37s
= 11y 51d 10h 2m 16.00s
이 함수는 다음 형식으로 초를 출력합니다. 11h 22m, 1y 244d, 42m 4s etc 원하는만큼 식별자를 표시하도록 max 변수를 설정합니다.
function secondsToString (seconds) {
var years = Math.floor(seconds / 31536000);
var max =2;
var current = 0;
var str = "";
if (years && current<max) {
str+= years + 'y ';
current++;
}
var days = Math.floor((seconds %= 31536000) / 86400);
if (days && current<max) {
str+= days + 'd ';
current++;
}
var hours = Math.floor((seconds %= 86400) / 3600);
if (hours && current<max) {
str+= hours + 'h ';
current++;
}
var minutes = Math.floor((seconds %= 3600) / 60);
if (minutes && current<max) {
str+= minutes + 'm ';
current++;
}
var seconds = seconds % 60;
if (seconds && current<max) {
str+= seconds + 's ';
current++;
}
return str;
}
0 일, 0 시간이 아닌 필요한 것만 표시하려면 ...
formatTime = function(time) {
var ret = time % 1000 + ' ms';
time = Math.floor(time / 1000);
if (time !== 0) {
ret = time % 60 + "s "+ret;
time = Math.floor(time / 60);
if (time !== 0) {
ret = time % 60 + "min "+ret;
time = Math.floor(time / 60);
if (time !== 0) {
ret = time % 60 + "h "+ret;
...
}
}
}
return ret;
};
Dan 답변의 도움으로 게시물 생성 시간 (DB에서 UTC로 검색해야 함)과 사용자 시스템 시간의 차이를 계산 한 다음 경과 시간을 표시하려면 이것을 생각해 냈습니다. 아래 기능
function dateToStr(input_date) {
input_date= input_date+" UTC";
// convert times in milliseconds
var input_time_in_ms = new Date(input_date).getTime();
var current_time_in_ms = new Date().getTime();
var elapsed_time = current_time_in_ms - input_time_in_ms;
function numberEnding (number) {
return (number > 1) ? 's' : '';
}
var temp = Math.floor(elapsed_time / 1000);
var years = Math.floor(temp / 31536000);
if (years) {
return years + ' year' + numberEnding(years);
}
//TODO: Months! Maybe weeks?
var days = Math.floor((temp %= 31536000) / 86400);
if (days) {
return days + ' day' + numberEnding(days);
}
var hours = Math.floor((temp %= 86400) / 3600);
if (hours) {
return hours + ' hour' + numberEnding(hours);
}
var minutes = Math.floor((temp %= 3600) / 60);
if (minutes) {
return minutes + ' minute' + numberEnding(minutes);
}
var seconds = temp % 60;
if (seconds) {
return seconds + ' second' + numberEnding(seconds);
}
return 'less than a second'; //'just now' //or other string you like;
}
예 : 사용법
var str = dateToStr('2014-10-05 15:22:16');
이것이 해결책입니다. 나중에 ":"로 분할하여 배열 값을 가져올 수 있습니다.
/**
* Converts milliseconds to human readeable language separated by ":"
* Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
*/
function dhm(t){
var cd = 24 * 60 * 60 * 1000,
ch = 60 * 60 * 1000,
d = Math.floor(t / cd),
h = '0' + Math.floor( (t - d * cd) / ch),
m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
return [d, h.substr(-2), m.substr(-2)].join(':');
}
//Example
var delay = 190980000;
var fullTime = dhm(delay);
console.log(fullTime);
저는 개체의 열렬한 팬이므로 https://metacpan.org/pod/Time::Seconds 에서 만들었습니다.
용법:
var human_readable = new TimeSeconds(986543).pretty(); // 11 days, 10 hours, 2 minutes, 23 seconds
;(function(w) {
var interval = {
second: 1,
minute: 60,
hour: 3600,
day: 86400,
week: 604800,
month: 2629744, // year / 12
year: 31556930 // 365.24225 days
};
var TimeSeconds = function(seconds) { this.val = seconds; };
TimeSeconds.prototype.seconds = function() { return parseInt(this.val); };
TimeSeconds.prototype.minutes = function() { return parseInt(this.val / interval.minute); };
TimeSeconds.prototype.hours = function() { return parseInt(this.val / interval.hour); };
TimeSeconds.prototype.days = function() { return parseInt(this.val / interval.day); };
TimeSeconds.prototype.weeks = function() { return parseInt(this.val / interval.week); };
TimeSeconds.prototype.months = function() { return parseInt(this.val / interval.month); };
TimeSeconds.prototype.years = function() { return parseInt(this.val / interval.year); };
TimeSeconds.prototype.pretty = function(chunks) {
var val = this.val;
var str = [];
if(!chunks) chunks = ['day', 'hour', 'minute', 'second'];
while(chunks.length) {
var i = chunks.shift();
var x = parseInt(val / interval[i]);
if(!x && chunks.length) continue;
val -= interval[i] * x;
str.push(x + ' ' + (x == 1 ? i : i + 's'));
}
return str.join(', ').replace(/^-/, 'minus ');
};
w.TimeSeconds = TimeSeconds;
})(window);
나는 좋은 '10 초 전 '스타일 문자열을 제공하는 다른 답변 중 하나를 정리했습니다.
function msago (ms) {
function suffix (number) { return ((number > 1) ? 's' : '') + ' ago'; }
var temp = ms / 1000;
var years = Math.floor(temp / 31536000);
if (years) return years + ' year' + suffix(years);
var days = Math.floor((temp %= 31536000) / 86400);
if (days) return days + ' day' + suffix(days);
var hours = Math.floor((temp %= 86400) / 3600);
if (hours) return hours + ' hour' + suffix(hours);
var minutes = Math.floor((temp %= 3600) / 60);
if (minutes) return minutes + ' minute' + suffix(minutes);
var seconds = Math.floor(temp % 60);
if (seconds) return seconds + ' second' + suffix(seconds);
return 'less then a second ago';
};
@Dan에 대한 유사한 접근 방식에 따라 @Royi Namir의 코드를 수정하여 쉼표 및 and로 문자열을 출력했습니다.
secondsToString = function(seconds) {
var numdays, numhours, nummilli, numminutes, numseconds, numyears, res;
numyears = Math.floor(seconds / 31536000);
numdays = Math.floor(seconds % 31536000 / 86400);
numhours = Math.floor(seconds % 31536000 % 86400 / 3600);
numminutes = Math.floor(seconds % 31536000 % 86400 % 3600 / 60);
numseconds = seconds % 31536000 % 86400 % 3600 % 60;
nummilli = seconds % 1.0;
res = [];
if (numyears > 0) {
res.push(numyears + " years");
}
if (numdays > 0) {
res.push(numdays + " days");
}
if (numhours > 0) {
res.push(numhours + " hours");
}
if (numminutes > 0) {
res.push(numminutes + " minutes");
}
if (numseconds > 0) {
res.push(numminutes + " seconds");
}
if (nummilli > 0) {
res.push(nummilli + " milliseconds");
}
return [res.slice(0, -1).join(", "), res.slice(-1)[0]].join(res.length > 1 ? " and " : "");
};
마침표가 없으므로 다음과 같이 그 뒤에 문장을 추가 할 수 있습니다.
perform: function(msg, custom, conn) {
var remTimeLoop;
remTimeLoop = function(time) {
if (time !== +custom[0]) {
msg.reply((secondsToString(time)) + " remaining!");
}
if (time > 15) {
return setTimeout((function() {
return remTimeLoop(time / 2);
}), time / 2);
}
};
// ...
remTimeLoop(+custom[0]);
}
custom[0]
기다리는 총 시간은 어디입니까 ? 시간을 2로 계속 나누고 타이머가 끝날 때까지 남은 시간을 경고하고 시간이 15 초 미만이면 경고를 중지합니다.
최신 버전의 Chrome 및 Firefox에서 지원되는 Intl.RelativeTimeFormat API가 있습니다.
몇 가지 예 :
let rtf = new Intl.RelativeTimeFormat("en");
rtf.format(-1, "day"); // 'yesterday'
rtf.format(-2, 'day'); // '2 days ago'
rtf.format(13.37, 'second'); // 'in 13.37 seconds'
그리고이 블로그 게시물 과 제안 자체 에 더 많은 내용 이 있습니다 .
function secondsToTimeString(input) {
let years = 0, days = 0, hours = 0, minutes = 0, seconds = 0;
let ref = [31536000,86400,3600,60,1];
for (let i = 0;i < ref.length;i++) {
let val = ref[i];
while (val <= input) {
input -= val;
if (i === 0) years++;
if (i === 1) days++;
if (i === 2) hours++;
if (i === 3) minutes++;
if (i === 4) seconds++;
}
return {년, 일,시, 분, 초}; }
'Development Tip' 카테고리의 다른 글
C # 생성자 오버로딩 (0) | 2020.11.25 |
---|---|
Sourcetree의 .gitignore 파일이 작동하지 않습니다. (0) | 2020.11.25 |
시간 O (n)에서 배열에서 중복 요소 찾기 (0) | 2020.11.25 |
Android ImageView : 너비 맞추기 (0) | 2020.11.25 |
Rails 4 앱의 이름을 바꾸는 방법은 무엇입니까? (0) | 2020.11.25 |