programing

Javascript 초에서 분, 초

randomtip 2022. 11. 22. 21:55
반응형

Javascript 초에서 분, 초

이것은 흔한 문제인데 어떻게 해결해야 할지 모르겠어요.다음 코드는 올바르게 동작합니다.

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(duration)
{   
    // Hours, minutes and seconds
    var hrs = ~~(duration / 3600);
    var mins = ~~((duration % 3600) / 60);
    var secs = ~~duration % 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에 붙이면 할 수 있는 '입니다).+에서 ""를 선택합니다.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)+

2020년 갱신

기본적인 수학과 간단한 Javascript를 사용하면 코드 몇 줄만으로 이 작업을 수행할 수 있습니다.

- " - " 변환7735 seconds로로 합니다.HH:MM:SS.


연산:

계산 사용:

  1. Math.floor()- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

Math.floor()함수는 지정된 수 이하의 최대 정수를 반환합니다.

  1. %산술 연산자(리머) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder

lember 연산자는 한 피연산자를 두 번째 피연산자로 나눈 나머지 피연산자를 반환합니다.항상 배당금의 징후를 포착합니다.

아래 코드를 확인하십시오.3600분수와 초수를 계산하는 데 사용되는 시간 및 나머지를 가져옵니다.

HOURS => 7735 / 3600 = 2 remainder 535

MINUTES => 535 / 60 = 8 remainder 55

SECONDS => 55


선행 0:

여기에서는, 많은 회답이 복잡한 방법을 사용하고 있습니다.시간, 분, 초수를 올바른 방법으로 표시해, 선두에 제로를 붙입니다.45,04기타. 이 조작은, 다음의 방법으로 실행할 수 있습니다.padStart()이 기능은 문자열에 대해 작동하므로 숫자를 문자열로 변환해야 합니다.toString().

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

padStart()method 는 결과 문자열이 지정된 길이에 도달할 때까지 현재 문자열을 다른 문자열(필요한 경우 최대 횟수)로 패딩합니다.패딩은 현재 문자열의 시작부터 적용됩니다.


코드:

function secondsToTime(e){
    const h = Math.floor(e / 3600).toString().padStart(2,'0'),
          m = Math.floor(e % 3600 / 60).toString().padStart(2,'0'),
          s = Math.floor(e % 60).toString().padStart(2,'0');
    
    return h + ':' + m + ':' + s;
    //return `${h}:${m}:${s}`;
}

console.log(secondsToTime(7735));  // 02:08:55

/*
secondsToTime(SECONDS) // HH:MM:SS 

secondsToTime(8)       // 00:00:08 
secondsToTime(68)      // 00:01:08
secondsToTime(1768)    // 00:29:28
secondsToTime(3600)    // 01:00:00
secondsToTime(5296)    // 01:28:16
secondsToTime(7735)    // 02:08:55
secondsToTime(45296)   // 12:34:56
secondsToTime(145296)  // 40:21:36
secondsToTime(1145296) // 318:08:16
*/

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(':')
}

네이티브 날짜 개체를 사용할 수도 있습니다.

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);

물론 이 솔루션은 시간 동안만 작동합니다.InSeconds가 24시간 미만입니다.

function secondsToMinutes(time){
    return Math.floor(time / 60)+':'+Math.floor(time % 60);
}

선행 0을 추가하려면 다음 작업을 수행합니다.

const secondsToMinSecPadded = time => {
  const minutes = "0" + Math.floor(time / 60);
  const seconds = "0" + (time - minutes * 60);
  return minutes.substr(-2) + ":" + seconds.substr(-2);
};


console.log(secondsToMinSecPadded(241));

나이스 앤 쇼트

모멘트.js

Moment.js사용하고 있는 경우는, 내장되어 있는 것을 사용할 수 있습니다.Duration물건

const duration = moment.duration(4825, 'seconds');

const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25

ES6를 사용하여 라이너 하나를 청소합니다.


const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);

내가 찾은 가장 간결한 방법은 단 한 줄로 실행할 수 있다.

let timeString = `${timeInSeconds/60|0}:${timeInSeconds%60}`

설명.

`${...}`
템플릿 리터럴문자열 자체에서 문자열로 식을 변환할 수 있습니다.
주의: IE와 호환되지 않습니다.

timeInSeconds/60|0
몇 초만에 분 단위로 변환됩니다(/60). 이것은 합리적인 숫자를 제공합니다.여기서부터는 비트 단위 OR( )을 사용하여 잘라냅니다.|0)

timeInSeconds%60
나머지(모듈로).변수의 나머지를 60으로 나눈 값을 제공합니다.


몇시간.

이 메서드는 다음과 같은 시간을 포함하도록 확장할 수 있습니다.

let timeString = `${timeInSeconds/60/60|0}:${timeInSeconds/60%60|0}:${timeInSeconds%60}`

이 프로세스를 반복하면 요일을 포함할 수도 있습니다.

1개의 라이너(시간에는 사용할 수 없음):

 function sectostr(time) {
    return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
 }

초 ~ 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));

다음 함수는 Days, Hours, 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());

이를 위한 보다 우아한 또 다른 솔루션은 다음과 같습니다.

/**
 * 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;
};
  function formatSeconds(s: number) {
    let minutes = ~~(s / 60);
    let seconds = ~~(s % 60);
    return minutes + ':' + seconds;
  }

0을 추가하는 경우, 예를 들어 단순히 사용할 수 있는 완전한 다른 함수는 필요하지 않습니다.

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);

그게 우리가 애초에 조건부 진술을 하는 이유야.

( condition ? true : false )그래서 예시가 show seconds가 아닌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>

이것을 시험해 보세요.
Second를 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;
}

1 - 다음을 사용하여 나머지 분할을 취득합니다.%이제 1분2를 완료하지 못한 초수를 합계에서 1단계에서 얻은 초수를 뺍니다.이제 회의록이 있습니다.

예를 들어 700초가 있다고 가정합니다.

seconds = 700%60); //40 seconds
minutes = (700 - (700%60))/60; //11
//11:40

더 빨리 끝낼 수 있는 방법을 생각하다가 이렇게 생각해낸 거야

var sec = parseInt(time);
var min=0;
while(sec>59){ sec-=60; min++;}

예를 들어 "time"을 분 및 초로 변환하는 경우:

// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1

제 의견을 말씀해주세요.

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
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`;
}

day.js

day.js사용하는 경우는, 이것을 사용해 주세요.

const dayjs = require('dayjs')
const duration = require('dayjs/plugin/duration') 
dayjs.extend(duration)

const time = dayjs.duration(100, 'seconds')

time.seconds() // 40
time.minutes() // 1
time.format('mm:ss') // 01:40

저는 밀리초를 다른 것의 하위 단위보다 그 자체의 단위로 생각하는 것을 선호합니다.그런 의미에서 0-999의 값을 갖게 되므로 다른 답변에서 보았던 것처럼 2개가 아닌 3번 패드를 사용해야 합니다.실장은 다음과 같습니다.

function format(n) {
   let mil_s = String(n % 1000).padStart(3, '0');
   n = Math.trunc(n / 1000);
   let sec_s = String(n % 60).padStart(2, '0');
   n = Math.trunc(n / 60);
   return String(n) + ' m ' + sec_s + ' s ' + mil_s + ' ms';
}

console.log(format(241));

https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/String/padStart

분, 과 패딩ES6 「패딩」)을 .00:00포맷)을 클릭합니다.와 seconds의 할 수 .~~(x)단축 플로어 조작입니다.

const padTime = n => ("" + n).padStart(2, 0);
const secondsToMinSec = time =>
  `${padTime(~~(time / 60))}:${padTime(time - ~~(time / 60) * 60)}`
;

for (let i = 0; i < 10; i++) {
  const seconds = ~~(Math.random() * 300);
  console.log(seconds, secondsToMinSec(seconds));
}

strftime.http(strftime github)는 최적의 시간 포맷 라이브러리 중 하나입니다.30KB로 매우 가볍고 효과적입니다.이를 사용하면 주로 네이티브 날짜 클래스에 의존하여 코드 한 줄에서 초를 시간으로 쉽게 변환할 수 있습니다.

새 날짜를 작성할 때 각 선택적 인수는 다음과 같이 배치됩니다.

new Date(year, month, day, hours, minutes, seconds, milliseconds);

따라서 모든 인수가 0으로 되어 있는 새로운 날짜를 초까지 초기화하면 다음과 같이 표시됩니다.

var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)

150초가 2분 30초임을 알 수 있습니다(작성일로부터 알 수 있습니다.그런 다음 strftime 형식("MM:SS"의 경우 %M:%S")을 사용하여 분 문자열을 출력합니다.

var mm_ss_str = strftime("%M:%S", date);
=> "02:30"

한 줄에 다음과 같이 표시됩니다.

var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"

또한 HH를 서로 교환하여 지원할 수 있습니다.초수에 근거한 MM:SS 및 MM:SS.예를 들어 다음과 같습니다.

# 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"

물론 시간 문자열이 다소 의미적이어야 할 경우 스트레이트할 형식을 쉽게 전달할 수 있습니다.

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!"

몇 분, 몇 초의 시간을 추적할 수 있는 충분한 코드를 입력했습니다.

다음 항목에 시간 계수를 추가할 수 있습니다.

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

언급URL : https://stackoverflow.com/questions/3733227/javascript-seconds-to-minutes-and-seconds

반응형