網頁Web-Javascript-即時更新日期時間

  • 9623
  • 0
  • Web
  • 2023-07-11

1.即時更新日期時間

2.客製化自己的日期時間

3.實作:客製化按鈕,使用function功能

 

1.即時更新日期時間

page.html

<html>
<head></head>

<!--網頁一載入時呼叫 功能: current_time() -->
<body onload="current_time()">
	<span id="current"></span>
</body>
</html>

<script>
function current_time(){
 document.getElementById('current').innerHTML = new Date();
 setTimeout('current_time()',1000); //每秒呼叫一次功能: current_time()
}
</script>

參考

https://codepen.io/yiruatstudio/pen/qBNKRNb

2.客製化自己的日期時間

<html>
<head></head>
<body onload="current_time()">
<span id="current"></span>
</body>
</html>
<script>

function mynow(){
	NowDate=new Date();
	h=NowDate.getHours();
	m=NowDate.getMinutes();
	s=NowDate.getSeconds();
}

function current_time(){
  mynow();
 document.getElementById('current').innerHTML = '現在時刻:'+h+'時'+m+'分'+s+'秒';
 setTimeout('current_time()',1000);
}
</script>

參考

<html>
<head></head>
<body onload="current_time()">
<span id="current"></span>
</body>
</html>
<script>
function current_time(){
 NowDate=new Date();
 h=NowDate.getHours();
 m=NowDate.getMinutes();
 s=NowDate.getSeconds(); 
 document.getElementById('current').innerHTML = '現在時刻:'+h+'時'+m+'分'+s+'秒';
 setTimeout('current_time()',1000);
}
</script>

參考

https://codepen.io/yiruatstudio/pen/RwRJKgZ

 

3.實作:客製化按鈕,使用function功能,點擊按鈕時並即時更新時間

按鈕功能:

建立三個功能(function),點擊按鈕時呼叫function,
按鈕1:日期時間
按鈕2:今天日期
按鈕3.現在時間


點選按鈕後:


1.日期時間: 顯示標準時間
2.今天日期: 只抓年/月/日
3.現在時間: 只抓時/分/秒

<html>
<head>
<title>日期、時間</title>
</head>
<body>
<button onclick="myDate()">日期時間:</button><span id="mToday"></span><Br>
<button onclick="mToday()">今天日期:</button><span id="mday"></span><Br>
<button onclick="mTime()">顯示時間:</button><span id="mT"></span><Br>
</body>
</html>
<script>
function mynow(){
  Today = new Date();
  yy=Today.getFullYear();
  mm=Today.getMonth()+1;
  dd=Today.getDate();
  h=Today.getHours();
  m=Today.getMinutes();
  s=Today.getSeconds(); 
}
function myDate(){
  mynow();
  document.getElementById("mToday").innerHTML = Today;
  setTimeout('myDate()',1000)
}
function mToday(){
  mynow();
  document.getElementById("mday").innerHTML = yy+"年"+mm+"月"+dd+"日";
  setTimeout('mToday()',1000)
}
function mTime(){
  mynow()
  document.getElementById("mT").innerHTML = h+":"+m+":"+s;
  setTimeout('mTime()',1000)
}
</script>

 

 

 

 

 

 

 

參考

Yiru@Studio - 關於我 - 意如