当前位置:网站首页>JS Date object
JS Date object
2022-06-26 07:49:00 【GHUIJS】
js date Objects are often needed in development , For example, pin punch , Jingdong limited time rush purchase, etc :
Next, let's learn from the basics js date object .
One 、date Object base
1. establish date object
new Date(); new Date(value); new Date(dateString); new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
// Returns the current point in time
console.log(new Date());//Mon Mar 08 2021 22:03:33 GMT+0800 ( China standard time )
// Represents the incoming year string
console.log(new Date("2021"))//Fri Jan 01 2021 08:00:00 GMT+0800 ( China standard time )
console.log(new Date("2021"))
// Go back to 2001 The year estimate is the object bug
console.log(new Date("3"))//Thu Mar 01 2001 00:00:00 GMT+0800 ( China standard time )
// It means 2021 March 5 No. In the morning 12.
console.log(new Date("2021 03 05"))
console.log(new Date("2021 3 5"))
// When a numeric parameter is passed in , You must pass in the year and year parameters
console.log(new Date(2020,3))//Wed Apr 01 2020 00:00:00 GMT+0800 ( China standard time )
console.log(new Date(2020))//Thu Jan 01 1970 08:00:02 GMT+0800 ( China standard time )
// When entering the month , From the month 0 Start counting ,0 Means January
console.log(new Date(2020,2,5,23,17,50))//Wed Apr 01 2020 00:00:00 GMT+0800 ( China standard time )
Two 、date Common methods
dateObj.get(set)Date() obtain ( Set up ) One day in the month
let date = new Date();
// It's today 202100309
console.log(date.getDate());//9
console.log(date.setDate(20));//1616202081402
console.log(new Date(date.setDate(20)))//Sat Mar 20 2021 09:01:21 GMT+0800 ( China standard time )
console.log(new Date(date.setDate(20)).getDate())//20
dateObj.getDay() Get a day of the week
let date = new Date();
// It's today 202100309
console.log(date.getDay());//2 Today is Tuesday No, setDay Method
dateObj.get(set)FullYear() obtain ( Set up ) year
let date = new Date();
// It's today 202100309
console.log(date.getFullYear());//2021
console.log(date.setFullYear(2050));//2530401084531
console.log(new Date(date.setFullYear(2050)));//Wed Mar 09 2050 09:11:24 GMT+0800 ( China standard time )
dateObj.get(set)Hours() obtain ( Set up ) Hours
let date = new Date();
console.log(date)//Tue Mar 09 2021 09:14:53 GMT+0800 ( China standard time )
// It's today 202100309
console.log(date.getHours());//9
console.log(date.setHours(18));//1615284893938
console.log(new Date(date.setHours(18)));//Tue Mar 09 2021 18:14:53 GMT+0800 ( China standard time )
dateObj.get(set)Milliseconds() obtain ( Set up ) The number of milliseconds of the time object
let date = new Date();
console.log(date)//Tue Mar 09 2021 09:14:53 GMT+0800 ( China standard time )
// It's today 202100309
console.log(date.getMilliseconds());// The return value range is 0~1000
dateObj.get(set)Minutes() obtain ( Set up ) minute
let date = new Date();
console.log(date)//Tue Mar 09 2021 09:22:06 GMT+0800 ( China standard time )
// It's today 202100309
console.log(date.getMinutes());//22
console.log(date.setMinutes(50));//1615254606043
console.log(new Date(date.setMinutes(50)));//Tue Mar 09 2021 09:50:06 GMT+0800 ( China standard time )
dateObj.get(set)Month() obtain ( Set up ) month
let date = new Date();
console.log(date)//Tue Mar 09 2021 09:22:06 GMT+0800 ( China standard time )
// It's today 202100309
console.log(date.getMonth());//2 The value range of the month is [0,11] namely :2 It means March
console.log(date.setMonth(5));//1615254606043 Here, the month is set to 6 month
console.log(new Date(date.setMonth(5)));//Tue Mar 09 2021 09:50:06 GMT+0800 ( China standard time )
dateObj.get(set)Seconds() obtain ( Set up ) second
dateObj.get(set)Time() Get the number of milliseconds of the object / Use the number of milliseconds passed in to set the time for the object
let date = new Date();
console.log(date)//Tue Mar 09 2021 09:22:06 GMT+0800 ( China standard time )
// It's today 202100309
console.log(date.getTime());//1615253961289
console.log(date.setTime(date.getTime()))//1615253961289
The following methods all return milliseconds :
console.log(new Date().valueOf())//1615698353800
console.log(new Date().getTime())//1615698353809
console.log(Date.now())//1615698353810
console.log(Date.now())//1615698353812
UTC and GMT The difference and connection
3、 ... and 、 Date formatting (moment.js)
console.log(new Date())//Tue Mar 09 2021 11:04:26 GMT+0800 ( China standard time )
console.log(moment().format("YYYY year MM month DD Japan "))//2021 year 03 month 09 Japan
console.log(moment(new Date(2020,4,20,5,20,20)).format("YYYY-M-DD hh:mm:ss"))//2020-5-20 05:20:20
Meaning , For more methods, please stamp moment.js The common method of
Four 、date Object usage scenarios
1. Get the day of the week the first day of the month ()
console.log(new Date())//Tue Mar 09 2021 11:54:51 GMT+0800 ( China standard time )
console.log(new Date(new Date().setDate(1)).getDay())//1
2. The countdown to two points in time
function countCown(endTime,timeDom,starTime = new Date()){
let date = countTime();
document.querySelector(timeDom).innerText = calTime(date);
var interval = setInterval(function(){
document.querySelector(timeDom).innerText = calTime(date);
date <= 0 ? clearInterval(interval) : date--;
},1000)
function countTime(){
return Math.floor( ( new Date(endTime).getTime() - new Date(starTime).getTime() ) / 1000 );
}
function calTime(timeSeconds){
return parseInt(calDay(timeSeconds)) > 0 ? calDay(timeSeconds) + ":" + calHours(timeSeconds) + ":" + calMinutes(timeSeconds) + ":" + calSeconds(timeSeconds) : calHours(timeSeconds) + ":" + calMinutes(timeSeconds) + ":" + calSeconds(timeSeconds);
function calDay(timeSeconds){
return addZero(Math.floor(timeSeconds / (3600 * 24)));
}
function calHours(timeSeconds){
return addZero(Math.floor(timeSeconds / 3600 % 24));
}
function calMinutes(timeSeconds){
return addZero(Math.floor(timeSeconds / 60 % 60));
}
function calSeconds(timeSeconds){
return addZero(Math.floor(timeSeconds % 60));
}
function addZero(num){
return num < 10 ? "0" + num : num;
}
}
}
countCown(new Date(2021,4,10,15,46),".time")
3. How many days are there in a year or a month
function calMonthDays(year,month){
let now = new Date();
year = year || now.getFullYear();
if((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0){
return [31,29,31,30,31,30,31,31,30,31,30,31][month - 1||now.getMonth()];
}else{
return [31,28,31,30,31,30,31,31,30,31,30,31][month - 1||now.getMonth()];
}
}
console.log(calMonthDays())// Nothing is sent to indicate the current year and month today 2021.3.9 31
console.log(calMonthDays(2020,2))//29
console.log(calMonthDays(2021,2))//28
console.log(calMonthDays(2021,3))//31
console.log(calMonthDays(2021,4))//30
4. Fill in the current page of the calendar table that is not part of this month
function calMonthDays(year,month){
let now = new Date();
year = year || now.getFullYear();
if((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0){
return [31,29,31,30,31,30,31,31,30,31,30,31][month||now.getMonth()];
}else{
return [31,28,31,30,31,30,31,31,30,31,30,31][month||now.getMonth()];
}
}
// Specify a date
let date = new Date(2021,2,20);
// Calculate the number of days in this month
let curMonthAllday = calMonthDays(date.getFullYear(),date.getMonth());
// Calculate the specified date No. 1
let firstDay = new Date(date.setDate(1));
// Calculate the last day of the specified date
let lastDay = new Date(date.setDate(curMonthAllday));
// Calculate the day of the week on the last day of the specified date
let lastDayWeek = lastDay.getDay();
console.log(lastDay,lastDayWeek)
// Calculate week one
let beforDays = firstDay.getDay();
let calendarbox = [];
for(let i = 1; i < beforDays; i++){
calendarbox.unshift(new Date(firstDay.setDate(firstDay.getDate() - 1)).getDate())
}
for(let i = 1; i <= curMonthAllday; i++){
calendarbox.push(i)
}
for(let i = 6; i >= lastDayWeek; i--){
calendarbox.push(7 - i)
}
console.log(calendarbox)
let timeStr = "";
for(let i = 0; i < calendarbox.length; i++){
timeStr += `<div class="time_item">${calendarbox[i]}</div>`
}
document.querySelector(".time").innerHTML = timeStr;
5、 ... and 、 Instance imitation
1. It is similar to the realization of the clock out time of nails
$(() => {
calNow()
setInterval(() => {
calNow();
},1000)
function calNow(){
let now = new Date();
let dataShow = addZero(now.getHours()) + ":" + addZero(now.getMinutes()) + ":" + addZero(now.getSeconds());
$(".time_show").text(dataShow);
}
function addZero(num){
return num < 10 ? "0" + num : num;
}
})
2. It is similar to the realization of the countdown of JD rush purchase
A little ...
边栏推荐
- Google Earth Engine(GEE) 01-中输入提示快捷键Ctrl+space无法使用的问题
- Jemter stress test - visualization tool - [usage]
- Basic use of swiperefreshlayout, local refresh of flutterprovider
- [UVM foundation] UVM_ Driver member variable req definition
- Getdrawingcache of view is empty. Solution: interview questions for Android audio and video development
- 技术分享 | MySQL:caching_sha2_password 快速问答
- Cloud native integration data warehouse heavy release
- buuresevewp
- Here is the command to display the disk space usage. Go ahead and pay attention to more wonderful things!
- Technology sharing | mysql:caching_ sha2_ Password quick Q & A
猜你喜欢
The "big grievances" in the workplace are not only physically tired, but also mentally emptied
Exploration and practice of incremental data Lake in station B
Sanic based services use celery to complete dynamic modification timing tasks
Redis(5)----浅谈压缩列表
Getdrawingcache of view is empty. Solution: interview questions for Android audio and video development
Median segmentation (find rules) - Niuke
Yyds dry inventory kubernetes easy service discovery and load balancing (11)
Two models of OSPF planning: double tower Raider and dog tooth crisscross
职场“大冤种”,不仅身累,心也被掏空……
Google Earth Engine(GEE) 01-中输入提示快捷键Ctrl+space无法使用的问题
随机推荐
Minor problems in importing D
Jemter 压力测试 -可视化工具支持-【安装篇】
Detach an entity from jpa/ejb3 persistence context
Redis(4)----浅谈整数集合
项目管理学习
arduino——ATtiny85 SSD1306 + DHT
How MySQL implements the RC transaction isolation level
Informatics Olympiad 1355: string matching problem (STRs)
A bold sounding and awesome operation - remake a Netflix
Chapter VII (structure)
Is it legal to open an account for compass stock trading software? Is it safe?
Getdrawingcache of view is empty. Solution: interview questions for Android audio and video development
技术分享 | MySQL:caching_sha2_password 快速问答
Solution to the problem of multi application routing using thinkphp6.0
Nine hours, nine people and nine doors (01 backpack deformation) - Niuke
[UVM practice] Chapter 3: UVM Fundamentals (3) field automation mechanism
Deeply analyze storage costs and find cost reduction solutions
职场“大冤种”,不仅身累,心也被掏空……
JS modularization
Es performance tuning and other features