1、日期转换成字符串
new Date().toLocaleString() //2024/6/28 16:13:38
str.replace(/\//g, "-") //2024-6-28 16:11:09 将/替换为-
str.replace(/-/g,"/") //将-替换为/
2、日期格式 yyyy-MM-dd HH:mm:ss
// 创建一个新的日期对象,如果不传参数则默认为当前日期和时间
var currentDate = new Date();
// 获取年、月、日、小时、分钟、秒
var year = currentDate.getFullYear();
var month = currentDate.getMonth() + 1; // 月份是从0开始的,所以需要+1
var day = currentDate.getDate();
var hour = currentDate.getHours();
var minute = currentDate.getMinutes();
var second = currentDate.getSeconds();
// 补零操作,确保月、日、小时、分钟、秒为两位数
month = ('0' + month).slice(-2);
day = ('0' + day).slice(-2);
hour = ('0' + hour).slice(-2);
minute = ('0' + minute).slice(-2);
second = ('0' + second).slice(-2);
// 组合字符串并输出
var formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
3、vue 日期选择
format="yyyy-MM-dd" value-format="yyyy-MM-dd" 格式化日期
<el-date-picker v-model="time" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请选择日期">
</el-date-picker>
4、判断当前月有几天
function getDaysInMonth(year, month) {
// JavaScript中的月份是从0开始的,所以需要减1
// 3、4、6、7、9、10、12月份有31天
// 1、3、5、7、8、10、12月份有30天
// 需要考虑闰年
month = month - 1;
let isLeapYear = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
let daysInMonth = [31, isLeapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return daysInMonth[month];
}
// 使用示例
let year = 2023; // 可以根据需要更改年份
let month = 2; // 可以根据需要更改月份
console.log(getDaysInMonth(year, month)); // 输出:28