2016-07-28 3 views
1

이 날짜가 & 시간 형식 2016-03-07 15:13:49입니다. 그리고 1 분 전, 1 시간 전 또는 1 년 전과 같이 지금부터 얼마나 오래 걸릴지에 따라 표시하고 싶습니다. ,시간을 yyyy-mm-dd hh : mm : ss 형식으로 변환하십시오.

+0

@RamanSahasi 답변, 내가 가지고있는 날짜 형식에 적용 할 수있다? –

+0

시간 형식을 변환하면됩니다. 내 대답을보고 코드 스 니펫을 실행하십시오. –

답변

1

당신은 js date 객체에 날짜 형식을 변환해야하고 정확성을 상관하지 않는 경우에 당신은 this 대답

var date = new Date('2016-03-07T15:13:49') 
 

 
document.write("js date: " + date + "<br><br>"); 
 
document.write("timesince: "); 
 

 
document.write(timeSince(date)); 
 

 
function timeSince(date) { 
 

 
    var seconds = Math.floor((new Date() - date)/1000); 
 

 
    var interval = Math.floor(seconds/31536000); 
 

 
    if (interval > 1) { 
 
     return interval + " years"; 
 
    } 
 
    interval = Math.floor(seconds/2592000); 
 
    if (interval > 1) { 
 
     return interval + " months"; 
 
    } 
 
    interval = Math.floor(seconds/86400); 
 
    if (interval > 1) { 
 
     return interval + " days"; 
 
    } 
 
    interval = Math.floor(seconds/3600); 
 
    if (interval > 1) { 
 
     return interval + " hours"; 
 
    } 
 
    interval = Math.floor(seconds/60); 
 
    if (interval > 1) { 
 
     return interval + " minutes"; 
 
    } 
 
    return Math.floor(seconds) + " seconds"; 
 
}

+0

고맙습니다. 해결책이 될 것입니다. –

+0

당신은 환영합니다 :) –

0
var past_date = new Date('2016-07-28T05:13:49'); // the date will come here 
var time_diff = new Date()- past_date;  // getting the difference between the past date and the current date 
var min = Math.floor(time_diff/60000); // Converting time in to minutes 
var seconds = 59, 
    minutes = Math.floor(min%60), 
    hours = Math.floor(min/60); 

if(hours > 24){ // Checking if the hours ids more than 24 to display as a day 
    var days = hours/24; 
    days = days.toFixed(0); 
    document.write("last updated:" + days + " days ago"); 
}else if(hours > 1){ // if time is less than the 24 hours it will display in hours 
    document.write("last updated:" + hours + " hours ago"); 
}else{ 
    document.write("last updated:" + minutes + " minutes ago"); 
} 
2

에서 timeSince 기능을 사용할 수 있습니다 나는 moment이 더 좋은 방법이라고 생각한다. 예를 들어

: 중복 문제

var m = require('moment'); 
m("2016-03-07 15:13:49","YYYY-MM-DD HH:mm:ss").fromNow(); // 5 months ago 
m("2016-07-28 12:13:49","YYYY-MM-DD HH:mm:ss").fromNow(); // 2 hours ago 
m("2016-07-28 13:13:49","YYYY-MM-DD HH:mm:ss").fromNow(); // 36 minutes ago 
m("2016-07-28 13:49:00","YYYY-MM-DD HH:mm:ss").fromNow(); // a minute ago 
m("2016-07-28 13:50:00","YYYY-MM-DD HH:mm:ss").fromNow(); // a few seconds ago 
관련 문제