使用js获取当前年月日的方法及格式整理汇总

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

使用js获取当前年月日的方法及格式整理汇总

不染-9732   2022-12-05 我要评论

1. 获取完整时间戳

var date = new Date(); ====》 Wed Sep 07 2022 17:18:30 GMT+0800 (中国标准时间) 小节2中的数据以此为基础

2. 整理年月日数据为: 2022-02-09 的格式

var year = date.getFullYear();

var month = date.getMonth() + 1;

var day = date.getDate();

month = (month > 9) ? month : (“0” + month);
day = (day < 10) ? (“0” + day) : day;
var today = year + “-” + month + “-” + day;

3. 关于日期数据的额外补充

date.getYear(); // 获取当前年份(2 位)
date.getFullYear(); // 获取完整的年份(4 位, 1970-???)
date.getMonth(); // 获取当前月份(0-11,0 代表 1 月)
date.getDate(); // 获取当前日(1-31)
date.getDay(); // 获取当前星期 X(0-6,0 代表星期天)
date.getTime(); // 获取当前时间(从 1970.1.1 开始的毫秒数)
date.getHours(); // 获取当前小时数(0-23)
date.getMinutes(); // 获取当前分钟数(0-59)
date.getSeconds(); // 获取当前秒数(0-59)
date.getMilliseconds(); // 获取当前毫秒数(0-999)
date.toLocaleDateString(); // 获取当前日期
date.toLocaleTimeString(); // 获取当前时间
date.toLocaleString( ); // 获取日期与时间

4. 判断闰年

 var date1 = new Date();
 Date.prototype.isLeapYear = function() {   
    return (0==this.getYear()%4&&((this.getYear()%100!=0)||(this.getYear()%400==0)));   
 }   
 console.log(date1.isLeapYear()); // false

5.日期格式化

/** 格式 YYYY/yyyy/YY/yy 表示年份  
  * MM/M 月份  
  * W/w 星期  
  * dd/DD/d/D 日期  
  * hh/HH/h/H 时间  
  * mm/m 分钟  
  * ss/SS/s/S 秒  
**/
//---------------------------------------------------  
Date.prototype.Format = function(formatStr)  {   
    var str = formatStr;   
    var Week = ['日','一','二','三','四','五','六'];  
  
    str=str.replace(/yyyy|YYYY/,this.getFullYear());   
    str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));   
  
    str=str.replace(/MM/,this.getMonth()>9?this.getMonth().toString():'0' + (this.getMonth()+1));      
    str=str.replace(/M/g,this.getMonth());   
 
 
    str=str.replace(/w|W/g,Week[this.getDay()]);   
  
    str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());   
    str=str.replace(/d|D/g,this.getDate());   
  
    str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' + this.getHours());   
    str=str.replace(/h|H/g,this.getHours());   
    str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0' + this.getMinutes());   
    str=str.replace(/m/g,this.getMinutes());   
  
    str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0' + this.getSeconds());   
    str=str.replace(/s|S/g,this.getSeconds());   
  
    return str;   
}   
var date=new Date();
var res=date.Format("yyyy-MM-dd HH:mm:ss  星期W");
console.info(res); //2022-01-07 16:18:36  星期五

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们