Skip to content

Commit acff873

Browse files
authored
演習問題バグ修正 (Date) (#605)
1 parent ce0812e commit acff873

File tree

2 files changed

+43
-11
lines changed

2 files changed

+43
-11
lines changed
Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,23 @@
11
const countdownBox = document.getElementById("countdown-box");
22

3-
const now = new Date();
4-
const remainingHours = 23 - now.getHours();
5-
const remainingMinutes = 59 - now.getMinutes();
6-
const remainingSeconds = 60 - now.getSeconds();
7-
countdownBox.textContent = `今日は残り${remainingHours}時間${remainingMinutes}${remainingSeconds}秒です。`;
3+
function getRemainingTime() {
4+
const now = new Date();
5+
const endOfDay = new Date(
6+
now.getFullYear(),
7+
now.getMonth(),
8+
now.getDate(),
9+
23,
10+
59,
11+
59,
12+
999,
13+
);
14+
const remainingTime = endOfDay.getTime() - now.getTime();
15+
16+
const hours = Math.floor(remainingTime / (1000 * 60 * 60));
17+
const minutes = Math.floor(remainingTime / (1000 * 60)) % 60;
18+
const seconds = Math.floor(remainingTime / 1000) % 60;
19+
20+
return `今日の残り時間: ${hours}時間 ${minutes}${seconds}秒です。`;
21+
}
22+
23+
countdownBox.textContent = getRemainingTime();

docs/2-browser-apps/03-class/index.mdx

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -402,16 +402,32 @@ document.write(false.toString()); // false
402402

403403
<Answer title="その日の残り時間">
404404

405-
`Date#getHour``Date#getMinutes``Date#getSeconds` を使います
405+
`Date#getTime` メソッドを使います
406406

407407
```js
408408
const countdownBox = document.getElementById("countdown-box");
409409

410-
const now = new Date();
411-
const remainingHours = 23 - now.getHours();
412-
const remainingMinutes = 59 - now.getMinutes();
413-
const remainingSeconds = 60 - now.getSeconds();
414-
countdownBox.textContent = `今日は残り${remainingHours}時間${remainingMinutes}${remainingSeconds}秒です。`;
410+
function getRemainingTime() {
411+
const now = new Date();
412+
const endOfDay = new Date(
413+
now.getFullYear(),
414+
now.getMonth(),
415+
now.getDate(),
416+
23,
417+
59,
418+
59,
419+
999,
420+
);
421+
const remainingTime = endOfDay.getTime() - now.getTime();
422+
423+
const hours = Math.floor(remainingTime / (1000 * 60 * 60));
424+
const minutes = Math.floor(remainingTime / (1000 * 60)) % 60;
425+
const seconds = Math.floor(remainingTime / 1000) % 60;
426+
427+
return `今日の残り時間: ${hours}時間 ${minutes}${seconds}秒です。`;
428+
}
429+
430+
countdownBox.textContent = getRemainingTime();
415431
```
416432

417433
<ViewSource url={import.meta.url} path="_samples/count-down" />

0 commit comments

Comments
 (0)