자바 스크립트 초에서 분 및 초
이것은 일반적인 문제이지만 해결 방법을 잘 모르겠습니다. 아래 코드는 정상적으로 작동합니다.
var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
그러나 1 시간 또는 3600 초에 도달하면 0 분 0 초가 반환됩니다. 이것을 피하여 어떻게 모든 분을 반환합니까?
감사
전체 분 수를 얻으려면 총 초 수를 60 (60 초 / 분)으로 나눕니다.
var minutes = Math.floor(time / 60);
그리고 남은 초를 얻으려면 전체 분에 60을 곱하고 총 초에서 빼십시오.
var seconds = time - minutes * 60;
이제 전체 시간도 가져 오려면 총 초 수를 3600 (60 분 / 시간 · 60 초 / 분)으로 먼저 나눈 다음 나머지 초를 계산하십시오.
var hours = Math.floor(time / 3600);
time = time - hours * 3600;
그런 다음 전체 분과 남은 초를 계산합니다.
보너스:
다음 코드를 사용하여 시간을 예쁘게 인쇄하십시오 (Dru에서 제안 함).
function str_pad_left(string,pad,length) {
return (new Array(length+1).join(pad)+string).slice(-length);
}
var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);
또 다른 멋진 솔루션 :
function fancyTimeFormat(time)
{
// Hours, minutes and seconds
var hrs = ~~(time / 3600);
var mins = ~~((time % 3600) / 60);
var secs = ~~time % 60;
// Output like "1:01" or "4:03:59" or "123:03:59"
var ret = "";
if (hrs > 0) {
ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
}
ret += "" + mins + ":" + (secs < 10 ? "0" : "");
ret += "" + secs;
return ret;
}
~~
의 약칭입니다 Math.floor
. 자세한 내용은 이 링크 를 참조하십시오.
사람들에게 초를 형식화하는 빠르고 간단하고 짧은 해결책을 기대하면서 M:SS
:
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
... 수행
기능은 받아들 중 하나Number
(선호) 또는String
(당신이 앞에 붙이는 반으로 줄일 수 2 변환 '처벌' +
에 대한 함수 호출의 인수 s
에 같이 fmtMSS(+strSeconds)
) 양의 정수 초 나타내는 s
인수로합니다.
예 :
fmtMSS( 0 ); // 0:00
fmtMSS( '8'); // 0:08
fmtMSS( 9 ); // 0:09
fmtMSS( '10'); // 0:10
fmtMSS( 59 ); // 0:59
fmtMSS( +'60'); // 1:00
fmtMSS( 69 ); // 1:09
fmtMSS( 3599 ); // 59:59
fmtMSS('3600'); // 60:00
fmtMSS('3661'); // 61:01
fmtMSS( 7425 ); // 123:45
고장:
function fmtMSS(s){ // accepts seconds as Number or String. Returns m:ss
return( s - // take value s and subtract (will try to convert String to Number)
( s %= 60 ) // the new value of s, now holding the remainder of s divided by 60
// (will also try to convert String to Number)
) / 60 + ( // and divide the resulting Number by 60
// (can never result in a fractional value = no need for rounding)
// to which we concatenate a String (converts the Number to String)
// who's reference is chosen by the conditional operator:
9 < s // if seconds is larger than 9
? ':' // then we don't need to prepend a zero
: ':0' // else we do need to prepend a zero
) + s ; // and we add Number s to the string (converting it to String as well)
}
참고 : (0>s?(s=-s,'-'):'')+
리턴 표현식 앞에 추가하여 음수 범위를 추가 할 수 있습니다 (실제로도 (0>s?(s=-s,'-'):0)+
작동 함).
기본 Date 객체를 사용할 수도 있습니다.
var date = new Date(null);
date.setSeconds(timeInSeconds);
// retrieve time ignoring the browser timezone - returns hh:mm:ss
var utc = date.toUTCString();
// negative start index in substr does not work in IE 8 and earlier
var time = utc.substr(utc.indexOf(':') - 2, 8)
// retrieve each value individually - returns h:m:s
var time = date.getUTCHours() + ':' + date.getUTCMinutes() + ':' + date.getUTCSeconds();
// does not work in IE8 and below - returns hh:mm:ss
var time = date.toISOString().substr(11, 8);
// not recommended - only if seconds number includes timezone difference
var time = date.toTimeString().substr(0, 8);
물론이 솔루션은 24 시간 미만의 timeInSeconds에 대해서만 작동합니다.)
function secondsToMinutes(time){
return Math.floor(time / 60)+':'+Math.floor(time % 60);
}
선행 0을 추가하려면 다음을 수행하십시오.
var minutes = "0" + Math.floor(time / 60);
var seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);
좋고 짧은
2019 최고의 변형
체재 hh:mm:ss
console.log(display(60 * 60 * 2.5 + 25)) // 2.5 hours + 25 seconds
function display (seconds) {
const format = val => `0${Math.floor(val)}`.slice(-2)
const hours = seconds / 3600
const minutes = (seconds % 3600) / 60
return [hours, minutes, seconds % 60].map(format).join(':')
}
하나의 라이너 (시간과 함께 일하지 않은) :
function sectostr(time) {
return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
}
ES6를 사용하여 하나의 라이너 청소
const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);
초받는-사람 h : mm : ss
var hours = Math.floor(time / 3600);
time -= hours * 3600;
var minutes = Math.floor(time / 60);
time -= minutes * 60;
var seconds = parseInt(time % 60, 10);
console.log(hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds));
이것에 대한 또 다른 훨씬 더 우아한 해결책은 다음과 같습니다.
/**
* Convert number secs to display time
*
* 65 input becomes 01:05.
*
* @param Number inputSeconds Seconds input.
*/
export const toMMSS = inputSeconds => {
const secs = parseInt( inputSeconds, 10 );
let minutes = Math.floor( secs / 60 );
let seconds = secs - minutes * 60;
if ( 10 > minutes ) {
minutes = '0' + minutes;
}
if ( 10 > seconds ) {
seconds = '0' + seconds;
}
// Return display.
return minutes + ':' + seconds;
};
다음 기능은 일, 시간, 분, 초를 얻는 데 도움이됩니다.
toDDHHMMSS(inputSeconds){
const Days = Math.floor( inputSeconds / (60 * 60 * 24) );
const Hour = Math.floor((inputSeconds % (60 * 60 * 24)) / (60 * 60));
const Minutes = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) / 60 );
const Seconds = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) % 60 );
let ddhhmmss = '';
if (Days > 0){
ddhhmmss += Days + ' Day ';
}
if (Hour > 0){
ddhhmmss += Hour + ' Hour ';
}
if (Minutes > 0){
ddhhmmss += Minutes + ' Minutes ';
}
if (Seconds > 0){
ddhhmmss += Seconds + ' Seconds ';
}
return ddhhmmss;
}
alert( toDDHHMMSS(2000));
이 모든 후, 또 다른 간단한 해결책 :
const time = new Date(null);
time.setSeconds(7530);
console.log(time.getHours(), time.getMinutes(), time.getSeconds());
제로를 추가하기 위해 실제로 예를 들어 간단히 사용할 수있는 다른 기능이 필요하지 않습니다.
var mins=Math.floor(StrTime/60);
var secs=StrTime-mins * 60;
var hrs=Math.floor(StrTime / 3600);
RoundTime.innerHTML=(hrs>9?hrs:"0"+hrs) + ":" + (mins>9?mins:"0"+mins) + ":" + (secs>9?secs:"0"+secs);
그렇기 때문에 우선 조건문이 있습니다.
(조건? true 인 경우 : false 인 경우) 초가 9 초 이상인 경우 초를 표시하는 것보다 그렇지 않으면 문자열 0을 앞에 추가하십시오.
var seconds = 60;
var measuredTime = new Date(null);
measuredTime.setSeconds(seconds); // specify value of SECONDS
var Time = measuredTime.toISOString().substr(11, 8);
document.getElementById("id1").value = Time;
<div class="form-group">
<label for="course" class="col-md-4">Time</label>
<div class="col-md-8">
<input type="text" class="form-control" id="id1" name="field">Min
</div>
</div>
시간의 분과 초를 추적하기에 충분한 코드를 작성했습니다.
할 수있는 일은 시간 요소를 추가하는 것입니다.
var hrd = time % (60 * 60 * 60);
var hours = Math.floor(hrd / 60);
var mind = hrd % 60;
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
var moreminutes = minutes + hours * 60
이것은 또한 당신에게 필요한 것을 줄 것입니다.
나는 이것을 끝내는 더 빠른 방법을 생각하고 있었고 이것이 내가 생각해 낸 것입니다.
var sec = parseInt(time);
var min=0;
while(sec>59){ sec-=60; min++;}
예를 들어 "시간"을 분과 초로 변환하려면 다음과 같이하십시오.
// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1
다른 해결책을 제안합니다.
function formatTime(nbSeconds, hasHours) {
var time = [],
s = 1;
var calc = nbSeconds;
if (hasHours) {
s = 3600;
calc = calc / s;
time.push(format(Math.floor(calc)));//hour
}
calc = ((calc - (time[time.length-1] || 0)) * s) / 60;
time.push(format(Math.floor(calc)));//minute
calc = (calc - (time[time.length-1])) * 60;
time.push(format(Math.round(calc)));//second
function format(n) {//it makes "0X"/"00"/"XX"
return (("" + n) / 10).toFixed(1).replace(".", "");
}
//if (!hasHours) time.shift();//you can set only "min: sec"
return time.join(":");
};
console.log(formatTime(3500));//58:20
console.log(formatTime(305));//05:05
console.log(formatTime(75609, true));//21:00:09
console.log(formatTime(0, true));//00:00:00
여러 가지 방법으로 해결되었음을 알고 있습니다. 속도 나 네임 스페이스 오염이 문제가되지 않는 After Effects 스크립트에이 기능이 필요했습니다. 나는 비슷한 것을 필요로하는 누군가를 위해 여기에 떨어 뜨립니다. 나는 또한 몇 가지 테스트를 작성하고 잘 작동했습니다. 코드는 다음과 같습니다.
Number.prototype.asTime = function () {
var hour = Math.floor(this / 3600),
min = Math.floor((this - hour * 3600) / 60),
sec = this - hour * 3600 - min * 60,
hourStr, minStr, secStr;
if(hour){
hourStr = hour.toString(),
minStr = min < 9 ? "0" + min.toString() : min.toString();
secStr = sec < 9 ? "0" + sec.toString() : sec.toString();
return hourStr + ":" + minStr + ":" + secStr + "hrs";
}
if(min){
minStr = min.toString();
secStr = sec < 9 ? "0" + sec.toString() : sec.toString();
return minStr + ":" + secStr + "min";
}
return sec.toString() + "sec";
}
내 두 센트를 넣어 :
function convertSecondsToMinutesAndSeconds(seconds){
var minutes;
var seconds;
minutes = Math.floor(seconds/60);
seconds = seconds%60;
return [minutes, seconds];
}
그래서 이건 :
var minutesAndSeconds = convertSecondsToMinutesAndSeconds(101);
다음과 같은 출력이 나타납니다.
[1,41];
다음과 같이 인쇄 할 수 있습니다.
console.log('TIME : ' + minutesSeconds[0] + ' minutes, ' + minutesSeconds[1] + ' seconds');
//TIME : 1 minutes, 41 seconds
시도해보십시오 : 초를 HOURS, MIN 및 SEC로 변환하십시오.
function convertTime(sec) {
var hours = Math.floor(sec/3600);
(hours >= 1) ? sec = sec - (hours*3600) : hours = '00';
var min = Math.floor(sec/60);
(min >= 1) ? sec = sec - (min*60) : min = '00';
(sec < 1) ? sec='00' : void 0;
(min.toString().length == 1) ? min = '0'+min : void 0;
(sec.toString().length == 1) ? sec = '0'+sec : void 0;
return hours+':'+min+':'+sec;
}
strftime.js (strftime github) is one of the best time formatting libraries. It's extremely light - 30KB - and effective. Using it you can convert seconds into time easily in one line of code, relying mostly on the native Date class.
When creating a new Date, each optional argument is positional as follows:
new Date(year, month, day, hours, minutes, seconds, milliseconds);
So if you initialize a new Date with all arguments as zero up to the seconds, you'll get:
var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)
You can see that 150 seconds is 2-minutes and 30-seconds, as seen in the date created. Then using an strftime format ("%M:%S" for "MM:SS"), it will output your minutes' string.
var mm_ss_str = strftime("%M:%S", date);
=> "02:30"
In one line, it would look like:
var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"
Plus this would allow you to interchangeable support HH:MM:SS and MM:SS based on the number of seconds. For example:
# Less than an Hour (seconds < 3600)
var seconds = 2435;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "40:35"
# More than an Hour (seconds >= 3600)
var seconds = 10050;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "02:47:30"
And of course, you can simply pass whatever format you want to strftime if you want the time string to be more or less semantic.
var format = 'Honey, you said you\'d be read in %S seconds %M minutes ago!';
strftime(format, new Date(0,0,0,0,0,1210));
=> "Honey, you said you'd be read in 10 seconds 20 minutes ago!"
Hope this helps.
export function TrainingTime(props) {
const {train_time } = props;
const hours = Math.floor(train_time/3600);
const minutes = Math.floor((train_time-hours * 3600) / 60);
const seconds = Math.floor((train_time%60));
return `${hours} hrs ${minutes} min ${seconds} sec`;
}
참고URL : https://stackoverflow.com/questions/3733227/javascript-seconds-to-minutes-and-seconds
'IT story' 카테고리의 다른 글
Android에서 애플리케이션 힙 크기 감지 (0) | 2020.06.18 |
---|---|
JVM을 어떻게 중단합니까? (0) | 2020.06.18 |
jQuery 유효성 검사 필수 선택 (0) | 2020.06.18 |
Brew를 사용하여 최신 버전의 Node를 설치하는 방법 (0) | 2020.06.18 |
MySQL에서 값이 숫자인지 감지 (0) | 2020.06.18 |