js日期对象的使用方式

JS日期对象的创建和使用方式

  • var oDate = new Date(); //创建日期对象

    • oDate.getFullyear(); //年

    • oDate.getMonth() + 1; //月份的格式是0-11 所以显示的时候我们要+1

    • oDate.getDate(); //日

    • oDate.getHours(); //时

    • oDate.getMinutes(); //分

    • oDate.getSeconds(); //秒

    • oDate.getDay(); // 星期 他返回的是0-6的数字 0代表周日 以此类推 1代表周一

实例:

  1. Date对象的创建以及简单的使用。
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			// 点击按钮后调用 SelTime() 方法 创建Date对象
			function SelTime(){
				var oDate = new Date();
				// 使用Date对象名.方法名设置显示格式	
				var time = oDate.getHours() + "时" + oDate.getMinutes() + "分" + oDate.getSeconds() + "秒";
				// 显示时间
				alert(time);
			}
		</script>
	</head>
	<body>
		<input type="button" value="查看时间" onclick="SelTime()" />
	</body>
</html>

效果图:弹出当前时间。
在这里插入图片描述
3. Date 输出样式的控制。

<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			// 点击按钮后调用 SelTime() 方法 创建Date对象
			function SelTime(){
				var oDate = new Date();
				// 使用Date对象名.方法名设置显示格式	
				var time = toDate(oDate.getHours()) + "时" + toDate(oDate.getMinutes()) + "分" + toDate(oDate.getSeconds()) + "秒";
				// 显示时间
				alert(time);
			}
			
			function toDate(len)	//这个方法用于判断是否是两位数   不是的话在前面补个0
			{
				if(len < 10)
				{
					return '0' + len;
				}else{
					return '' + len;
				}
			}
		</script>
	</head>
	<body>
		<input type="button" value="查看时间" onclick="SelTime()" />
	</body>
</html>

效果图:加上这个方法后实现了自动补0的效果。
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章