30
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascriptで1秒毎の現在時刻の表示

Last updated at Posted at 2017-10-11

javascriptで時間の表示を行なう

javascriptのお勉強に1秒毎に現在時刻を表示させたときのメモ

実装コード

<!DOCTYPE html>
<html lang="ja">
<head>
	<meta charset="utf-8">
	<title>時間の表示</title>
</head>
<body>
	<h1 id="time"></h1>
	<script>
	time();
	function time(){
		var now = new Date();
		document.getElementById("time").innerHTML = now.toLocaleTimeString();
	}
	setInterval('time()',1000);
	</script>
</body>
</html>

こんな感じになる。
date2.gif

toLocaleTimeString()toLocaleString()にすると日付も表示される。
image.png

コードの説明

Dateオブジェクトのインスタンスを作成し変数nowに入れる

var now = new Date();

toLocaleTimeString()メソッドの結果をhtmlに表示

document.getElementById("time").innerHTML = now.toLocaleTimeString();

1000ミリ秒ごとに表示

setInterval('time()',1000);
30
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?