实现代码如下:
获取几个月之后的时间和几天之后的时间:
- DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>时间戳转换title>
- head>
- <body>
- <script src="./jquery/jquery.min.js">script>
- <script>
- $(function(){
- let time='2023-11-17';
- let return_month_time=getLastMonthDay(time,3);
- console.log('固定时间为:',time,'返回的3个月后时间为:',return_month_time)
- let return_day_time=getLastDay(time,3);
- console.log('固定时间为:',time,'返回的n天后时间为:',return_day_time)
- // 获取n天之后的年月日
- function getLastDay(day_value,n){
- var last_day=new Date(day_value);
- last_day.setDate(last_day.getDate()+n);
- let data_r=new Date(last_day.getTime());
- let return_month=data_r.getMonth()+1;
- if (return_month < 10) {
- return_month = '0' + return_month;
- }
- let return_day=data_r.getDate();
- if (return_day < 10) {
- return_day = '0' + return_day;
- }
- return (data_r.getFullYear()+'-'+return_month+'-'+return_day);
-
- }
- // 获取3个月零1天的年月日
- function getLastMonthDay(day_value,n){
- var dateArr = day_value.split('-');
- let year = dateArr[0]; //获取当前日期的年份
- let month = dateArr[1]; //获取当前日期的月份
- let day = dateArr[2]; //获取当前日期的日
-
- let new_day = new Date(year,month , 0);// 固定时间年月日
- new_day = new_day.getDate(); //获取固定日期中的月的天数
- let new_year = year;
- let after_month = parseInt(month) + parseInt(n); // 2 是指的是获取几个后的时间 3就是三个月后的
- if (after_month > 12) {
- new_year = parseInt(new_year) + parseInt((parseInt(after_month) / 12 == 0 ? 1 : parseInt(after_month) / 12));
- after_month = parseInt(after_month) % 12;
- }
- let new_day2 = day;// 固定日期的日
- let new_days2 = new Date(new_year, after_month, 0);
- new_days2 = new_days2.getDate();// 获取3个月后的日
- console.log(new_day2,'eeee',new_days2)
- // 判断n个月之后有没有31号,如果没有,就拿小的日赋值给大的日
- if (new_day2 > new_days2) {
- new_day2 = new_days2;
- }
- // n个月后的年月日
- let t2 = new_year + '-' + after_month + '-' + new_day2;
- console.log('3个月后的年月日为',t2)
- var last_day=new Date(t2);
- last_day.setDate(last_day.getDate()+1);
-
- let data_r=new Date(last_day.getTime());
- let return_month=data_r.getMonth()+1;
- if (return_month < 10) {
- return_month = '0' + return_month;
- }
- let return_day=data_r.getDate();
- if (return_day < 10) {
- return_day = '0' + return_day;
- }
- return (data_r.getFullYear()+'-'+return_month+'-'+return_day);
-
- }
- })
- script>
- body>
- html>
其他函数使用:
获取JavaScript 的时间使用内置的Date函数完成
var mydate = new Date();
mydate.getYear(); //获取当前年份(2位)
mydate.getFullYear(); //获取完整的年份(4位,1970-????)
mydate.getMonth(); //获取当前月份(0-11,0代表1月)
mydate.getDate(); //获取当前日(1-31)
mydate.getDay(); //获取当前星期X(0-6,0代表星期天)
mydate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
mydate.getHours(); //获取当前小时数(0-23)
mydate.getMinutes(); //获取当前分钟数(0-59)
mydate.getSeconds(); //获取当前秒数(0-59)
mydate.getMilliseconds(); //获取当前毫秒数(0-999)
mydate.toLocaleDateString(); //获取当前日期
var mytime=mydate.toLocaleTimeString(); //获取当前时间
mydate.toLocaleString( ); //获取日期与时间
其他使用方法可参看:jquery new date函数_mob64ca12d8821d的技术博客_51CTO博客
目前我用到的就这些,有其他要求再做补充