2016-08-24 2 views
1

매월 15 일로 카운트 다운을 설정해야합니다. 15 번째 카운트 다운에 필요한 차이 값을 성공적으로 얻을 수 있습니다.카운트 다운 값 반환 0

차이를 계산 한 후 일, 시간, 분, 초를 계산합니다. 일 이외의 다른

모든이를 시도 0

export default React.createClass({ 
    tick: function() { 
    var currentDate = new Date(); 
    var date_till_15 = new Date(); 

    if (currentDate.getDate() < 15) { 
     var days_till_15 = 15 - currentDate.getDate(); 
     date_till_15 = new Date(date_till_15.setDate(currentDate.getDate() + days_till_15)); 
    } else if(currentDate.getDate() > 15){ 
     date_till_15 = new Date(date_till_15.setMonth(currentDate.getMonth() + 1)); 
     date_till_15 = new Date(date_till_15.setDate(15)); 
    } 

    var difference = date_till_15 - currentDate; 
    var daysLeft = 0, hoursLeft = 0, minutesLeft = 0, secondsLeft = 0; 

    if (difference > 0) { 
     daysLeft = Math.floor(difference/(1000*60*60*24)); 
     difference -= daysLeft * (1000*60*60*24); 
     hoursLeft = Math.floor(difference/(1000*60*60)); 
     difference -= hoursLeft * (1000*60*60); 
     minutesLeft = Math.floor(difference/(1000*60)); 
     difference -= minutesLeft * (1000*60); 
     secondsLeft = Math.floor(difference/1000); 

     this.setState({ 
     days: daysLeft, 
     hours: hoursLeft, 
     minutes: minutesLeft, 
     seconds: secondsLeft 
     }); 
    } else { 
     clearInterval(this.timeInterval); 
     this.setState({ expired: true }); 
    } 
    }, 

    componentDidMount: function(){ 
    this.timeInterval = setInterval(this.tick.bind(this), 1000); 
    }, 

    render() { 
    return (
     <div> 
     {this.state && 
      <div> 
      <div>{this.state.days}</div> 
      <div>{this.state.minutes}</div> 
      </div> 
     } 
     </div> 
    ) 
    } 
}); 
+1

하지 않음이 문제에 대한 해결책을하지만 Moment.js에 볼 수 있었다, 그것보다 훨씬 쉽게 네이티브 Date() 클래스로 작업합니다. http://momentjs.com/ – jered

+0

확실히 사용하십시오 – John

+0

코드를 올바르게 형식화 할 수 있다고 생각하십니까? 현재 상태에서 읽기가 매우 어렵습니다. –

답변

0

의 값을 반환 정확히

console.log(getTimeToNext(15)); 

function getTimeToNext(dayOfMonth) { 
var currentDate = new Date(); 
var target; 
if (currentDate.getDate() < dayOfMonth) { 
    target = new Date(
    currentDate.getFullYear(), 
    currentDate.getMonth(), 
    dayOfMonth, 0, 0, 0, 0); 
} else { 
    var currentMonth = currentDate.getMonth(); 
    if (currentMonth === 11) { 
     target = new Date(
     currentDate.getFullYear() + 1, 
     0, 
     dayOfMonth, 0, 0, 0, 0); 
    } else { 
     target = new Date(
     currentDate.getFullYear(), 
     currentMonth + 1, 
     dayOfMonth, 0, 0, 0, 0); 
    } 
} 

var delta = target - currentDate; 
var daysLeft = Math.floor(delta/(1000*60*60*24)); 
delta -= daysLeft * (1000*60*60*24); 
var hoursLeft = Math.floor(delta/(1000*60*60)); 
delta -= hoursLeft * (1000*60*60); 
var minutesLeft = Math.floor(delta/(1000*60)); 
delta -= minutesLeft * (1000*60); 
var secondsLeft = Math.floor(delta/(1000)); 

return { 
    days: daysLeft, 
    hours: hoursLeft, 
    minutes: minutesLeft, 
    seconds: secondsLeft}; 
}