Case code for Date in JavaScript

1 Introduction

Creates a JavaScript Date instance that represents a moment in time. Date objects are based on the Unix Time Stamp, which is the number of milliseconds that have elapsed since January 1, 1970 (UTC).

2. Case

2.1 Basic use of Date object

		var date = new Date()
		console.log(date);  //Fri Oct 28 2022 09:37:54 GMT+0800 (中国标准时间)
		var date1 = new Date('2019-5-1')
		console.log(date1); //Wed May 01 2019 00:00:00 GMT+0800 (中国标准时间)

2.2 Format date month day week

		var date = new Date()
		var year = date.getFullYear()  //年份
		var month = date.getMonth() + 1  //月份 返回的月份+1
		var dates = date.getDate() //几号
		var arr = ['星期日', '星期一', , '星期二', '星期三', '星期四', '星期五', '星期六']
		var day = date.getDay()  //周日返回的是0,周一返回的是1
		console.log(year + '年' + month + '月' + dates + '日' + arr[day]);  //2022年10月28日星期四

2.3 Format date, month, day, week, hour, minute and second

	var date = new Date()
		var year = date.getFullYear()  //年份
		var month = date.getMonth() + 1  //月份 返回的月份+1
		var dates = date.getDate() //几号
		var arr = ['星期日', '星期一', , '星期二', '星期三', '星期四', '星期五', '星期六']
		var day = date.getDay()  //周日返回的是0,周一返回的是1

		// 通过函数来格式化时分秒
		function getshifenmiao() {
    
    
			var date = new Date()
			var hour = date.getHours()
			hour = hour < 10 ? '0' + hour : hour   //通过正则表达式:要是小于10,就在前面添加一个0
			var minute = date.getMinutes()
			minute = minute < 10 ? '0' + minute : minute
			var s = date.getSeconds()
			s = s < 10 ? '0' + s : s
			return hour + ':' + minute + ':' + s
		}

		console.log(year + '年' + month + '月' + dates + '日' + arr[day] + ' ' + getshifenmiao());  //2022年10月28日星期四 09:48:30

2.4 Get the number of milliseconds since January 1, 1970

		var date = new Date()
		console.log(date.valueOf());  //1666921964254
		console.log(date.getTime());  //1666921964254

		// 2.简单的写法
		var date = +new Date()
		console.log(date);     //1666921964254

		// 3.H5新增的
		console.log(Date.now());       //1666921964254

2.5 Countdown through user input (key point)

		function daojishi(time) {
    
    
			var nowTime = +new Date()  //距离1970 年 1 月 1 日的毫秒数
			var inputTime = +new Date(time) //用户输入的日期 格式:2022-12-1 12:12:12
			var stime = (inputTime - nowTime) / 1000  //用户输入的秒数-1970秒数=倒计时的秒数
			var tian = parseInt(stime / 60 / 60 / 24)  //整数格式输出 秒/60=分 分/60=时 时/24=天 时%24=余下的时 秒%60=余下的秒 分%60=余下的分
			tian = tian < 10 ? '0' + tian : tian
			var hour = parseInt(stime / 60 / 60 % 24)
			hour = hour < 10 ? '0' + hour : hour
			var fen = parseInt(stime / 60 % 60)
			fen = fen < 10 ? '0' + fen : fen
			var miao = parseInt(stime % 60)
			miao = miao < 10 ? '0' + miao : miao
			return '还剩' + tian + '天' + hour + '时' + fen + '分' + miao + '秒'
		}
		console.log(daojishi('2022-12-1 12:12:12')); //还剩34天00时12分42秒

Guess you like

Origin blog.csdn.net/m0_62496369/article/details/127565529