From 1d38a9b2b7742e07deee056ce2e3e4b55e90cc28 Mon Sep 17 00:00:00 2001 From: nzambello Date: Fri, 1 Jan 2021 00:00:39 +0100 Subject: [PATCH] fix: generalization countdown for any year --- src/App/index.js | 71 +++++++++++++++++++++++++++--------------------- 1 file changed, 40 insertions(+), 31 deletions(-) diff --git a/src/App/index.js b/src/App/index.js index 8d108d2..3cf234e 100644 --- a/src/App/index.js +++ b/src/App/index.js @@ -1,45 +1,54 @@ -import React, { Component } from 'react'; -import './index.scss'; +import React, { Component } from 'react' +import './index.scss' -const _second = 1000; -const _minute = _second * 60; -const _hour = _minute * 60; -const _day = _hour * 24; +const _second = 1000 +const _minute = _second * 60 +const _hour = _minute * 60 +const _day = _hour * 24 class App extends Component { constructor() { - super(); + super() - const now = new Date(); - let imWaitingForDrinking = true; // of course default to true - let year = now.getFullYear() + 1; + const now = new Date() + let imWaitingForDrinking = true // of course default to true + let year = now.getFullYear() + 1 let countdownData = {} if (now.getMonth() === 0 && now.getDate() === 1) { - imWaitingForDrinking = false; - year = now.getFullYear(); - } - else { - countdownData = this.getMissingTime(now); + imWaitingForDrinking = false + year = now.getFullYear() + } else { + countdownData = this.getMissingTime(now) } this.state = { isNewYear: !imWaitingForDrinking, newYear: year, countdownID: null, - countdownData: countdownData, - }; + countdownData: countdownData + } } - getMissingTime = now => { - const midnight = new Date('2019-01-01 00:00'); - const delta = midnight - now; + getMissingTime = (now) => { + const newYear = now.getFullYear() + 1 - return { - days: Math.floor(delta / _day), - hours: Math.floor((delta % _day) / _hour), - minutes: Math.floor((delta % _hour) / _minute), - seconds: Math.floor((delta % _minute) / _second), + if (this.state && this.state.newYear && this.state.newYear === now.getFullYear()) { + this.setState({ + isNewYear: true + }) + + return this.state.countdownData + } else { + const midnight = new Date(`${newYear}-01-01 00:00`) + const delta = midnight - now + + return { + days: Math.floor(delta / _day), + hours: Math.floor((delta % _day) / _hour), + minutes: Math.floor((delta % _hour) / _minute), + seconds: Math.floor((delta % _minute) / _second) + } } } @@ -86,12 +95,12 @@ class App extends Component {

Happy New Year!

- Welcome to {newYear}! + Welcome to {newYear}!

-
-
+
+
)} @@ -99,7 +108,7 @@ class App extends Component {

Countdown to {newYear}

- {getCountdownMarkup(countdownData['days'], 's')} + {getCountdownMarkup(countdownData['days'], 'd')} {getCountdownMarkup(countdownData['hours'], 'h')} {getCountdownMarkup(countdownData['minutes'], 'm')} {getCountdownMarkup(countdownData['seconds'], 's')} @@ -107,8 +116,8 @@ class App extends Component {
)}
- ); + ) } } -export default App; +export default App