Home >Web Front-end >JS Tutorial >Learn date and time processing functions in JavaScript
Learn date and time processing functions in JavaScript
Date and time are very important in daily life, and are also essential in program development. JavaScript provides many built-in functions for handling date and time operations. This article will introduce some commonly used date and time processing functions and give specific code examples.
let now = new Date(); console.log(now); // 打印当前日期和时间
let date = new Date(2022, 0, 1); // 2022年1月1日 console.log(date);
let timestamp = Date.parse("2022-01-01"); // 将日期字符串转换为毫秒数 console.log(timestamp);
let date = new Date(); console.log(date.getFullYear()); // 获取当前年份
let date = new Date(); console.log(date.getMonth() + 1); // 获取当前月份,+1是因为月份从0开始计数
let date = new Date(); console.log(date.getDate()); // 获取当前日期
let date = new Date(); console.log(date.getHours()); // 获取当前小时
let date = new Date(); console.log(date.getMinutes()); // 获取当前分钟
let date = new Date(); console.log(date.getSeconds()); // 获取当前秒数
let date1 = new Date("2022-01-01"); let date2 = new Date("2023-01-01"); let diff = Math.floor((date2 - date1) / (1000 * 60 * 60 * 24)); // 计算两个日期之间相差的天数 console.log(diff);
let date = new Date("2022-01-01"); date.setDate(date.getDate() + 7); // 增加7天 console.log(date);
let date = new Date(); let formattedDate = date.toLocaleString("zh-CN", { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }); console.log(formattedDate);
The above code will output a formatted string similar to "Saturday, January 1, 2022".
Summary:
In JavaScript, date and time processing is a very important task. By using the built-in Date object and corresponding methods, we can easily manipulate and format dates and times. This article introduces some commonly used processing functions and gives specific code examples. I hope this article can be helpful to you in learning date and time processing in JavaScript.
The above is the detailed content of Learn date and time processing functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!