2017-02-19 5 views
0

나는이 우수한 함수를 HH : MM : SS에 사용하고 있지만 HH : MM 만 반환하도록 수정하거나 초를 버리거나 반올림하는 방법은 무엇입니까?초를 HH-MM으로 변환 JavaScript가 있습니까?

function formatSeconds(seconds) 
{ 
    var date = new Date(1970,0,1); 
    date.setSeconds(seconds); 
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1"); 
} 
+0

타사 라이브러리를 사용할 의향이 있습니까? MomentJS는 시간과 날짜를 처리하기에 좋은 도구입니다. –

+0

초가 1 일보다 길면 잘못된 값을 얻게됩니다. – RobG

답변

0

날짜 형식을 사용하여 초를 형식화 할 때의 문제점은 24 시간보다 긴 시간과 날짜 변경을 처리 할 수 ​​없다는 것입니다.

function formatSeconds(seconds) { 
 
    function z(n) {return (n < 10 ? '0' : '') + n;} 
 
    return z(seconds/3600 | 0) + ':' + z((seconds % 3600)/60 | 0) 
 
} 
 

 
// Some examples 
 
[0,1,61,3600,3660,765467].forEach(function (seconds) { 
 
    console.log(seconds + ' -> ' + formatSeconds(seconds)) 
 
});

없음 날짜, 아니 정규 표현식, 아니 라이브러리, 종속 이제까지 인 ECMAScript를 지원하는 모든 호스트에서 작동 : 간단하게 필요에 따라 값을 포맷하지 않습니다.

3
function formatSeconds(seconds) 
{ 
    var date = new Date(1970,0,1); 
    date.setSeconds(seconds); 
    return date.toTimeString().replace(/.*?(\d{2}:\d{2}).*/, "$1"); 
} 

마지막 \d{2}를 제거하고 이상적인 방법은 moment.js을 사용하는 것입니다하지만 처음 *

0

?를 추가하지만, 사용자 정의 기능을 사용하고자하는 경우, 당신은 이런 식으로 뭔가를 시도 할 수 있습니다 :

function formatSeconds(milliseconds, format) { 
 
    var dateObj = new Date(milliseconds); 
 

 
    function getDoubleDigits(value){ 
 
    return ("0" + value).slice(-2) 
 
    } 
 
    
 
    var o = { 
 
    DD: getDoubleDigits(dateObj.getDate()), 
 
    MM: getDoubleDigits(dateObj.getMonth() + 1), 
 
    YY: dateObj.getYear(), 
 
    YYYY: dateObj.getFullYear(), 
 
    hh: getDoubleDigits(dateObj.getHours()), 
 
    mm: getDoubleDigits(dateObj.getMinutes()), 
 
    ss: getDoubleDigits(dateObj.getSeconds()) 
 
    } 
 
    
 
    var dilimeter = format.match(/[^\w]/)[0]; 
 
    return format.split(dilimeter).map(function(f){ 
 
    return o[f]; 
 
    }).join(dilimeter); 
 
} 
 

 
var today = new Date(); 
 
console.log(formatSeconds(+today, "DD-MM-YYYY")) 
 
console.log(formatSeconds(+today, "hh:mm"))

+0

moment.js가 "이상적인"이유는 무엇입니까? 필요한 형식을 생성하는 함수는 단지 2 줄의 코드입니다. – RobG

+0

@RobG 필요한 것보다 더 많이 처리하기 때문에. OP는이 기능을 사용할 수 있도록 시간을 처리합니다. 그런 다음 또 다른 형식이 필요할 경우 다른 기능을 작성합니다. 제네릭 함수를 만들려고했지만 순간이 이미 날짜 문제를 해결했으며 휠 재발견에 과도한 부담이되었습니다. 네,이 사건에 대한 순간을 사용하여 과잉이지만, 제안으로, 나는 datetime 조작에 대한 더 나은 순간이라고 말하고 싶지만 – Rajesh

관련 문제