網頁Web-Javascript-日期、時間,Date() 使用方式

  • 7994
  • 0
  • Web
  • 2023-07-04

1.抓取目前標準時間

2.把抓到的標準日期時間顯示在網頁上

3.抓出 "年、月、日、時、分、秒"

4.顯示格式:

顯示日期時間:0000/00/00 下午4:33:41

顯示日期:0000/00/00

顯示時間:下午00:00:00

5.實作:

按鈕功能:

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

 

1.抓取目前標準時間
<script>

Today = Date();

console.log(Today);

</script>

 參考

2.把抓到的標準日期時間顯示在網頁上
<html>
	<head>
		<title>MyPage</title>
	</head>
	
<body>

</body> 
</html>

<script>


Today = Date();

document.write("標準時間:<br><b>"+Today+"</b><br>");

</script>

參考

3.抓出 "年、月、日、時、分、秒"


#注意:月的部分抓完後要+1

<html>
    <head>
        <title>MyPage</title>
    </head>
    
<body>

</body> 
</html>

<script>

Today = new Date();
console.log(Today);

y=Today.getFullYear();
console.log("年:"+y);

mh=(Today.getMonth()+1);
console.log("月:"+mh);

d=Today.getDate();
console.log("日:"+d);

h=Today.getHours();
console.log("時:"+h);

m=Today.getMinutes();
console.log("分:"+m);

s=Today.getSeconds(); 
console.log("秒:"+s);

</script>

參考

4.顯示格式

顯示日期時間:0000/00/00 下午4:33:41

顯示日期:0000/00/00

顯示時間:下午00:00:00

const date = new Date()

console.log(date.toLocaleString())     //2023/2/14 下午6:29:11
console.log(date.toLocaleDateString()) //2023/2/14
console.log(date.toLocaleTimeString()) //下午6:29:11

參考

5.實作:

按鈕功能:

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

程式碼參考:

參考

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

<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>
Today = new Date();

yy=Today.getFullYear();
mm=Today.getMonth()+1;
dd=Today.getDate();
h=Today.getHours();
m=Today.getMinutes();
s=Today.getSeconds(); 

function myDate(){
	document.getElementById("mToday").innerHTML = Today;
}

function mToday(){
	document.getElementById("mday").innerHTML = yy+"年"+mm+"月"+dd+"日";
}

function mTime(){
	document.getElementById("mT").innerHTML = h+":"+m+":"+s;
}
</script>

 

nn=new Date(new Date().getTime()+1000*60*15);//現在時間轉毫秒後+15分鐘後

 

轉UTC+8 (字串)

toUTCString(Today);
function toUTCString(Today){
    console.log(new Date(Today).toUTCString());//Sat, 12 Feb 2022 05:30:32 GMT
}

直接顯示台北時間

timenow=new Date().toLocaleString('zh-TW', {timeZone: 'Asia/Taipei'})
//2022/2/12 下午1:30:32

 

Yiru@Studio - 關於我 - 意如