JavaScript获取当前时间及格式化
2017-12-09 00:00
441 查看
一、代码示例
/** * Created by Administrator on 2017/12/9. * 以 2017/12/9 11:52:15为例 */ //为Date类型拓展一个format方法,用于格式化日期 Date.prototype.format = function (format) //author: meizz { var o = { "M+": this.getMonth() + 1, //month "d+": this.getDate(), //day "h+": this.getHours(), //hour "m+": this.getMinutes(), //minute "s+": this.getSeconds(), //second "q+": Math.floor((this.getMonth() + 3) / 3), //quarter "S": this.getMilliseconds() //millisecond }; if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); return format; }; $(document).ready(function(){ var myDate = new Date(); console.log(myDate); console.log(myDate.getYear()); // 获取当前年份(2位) 2017 - 1900 = 117 @Deprecated console.log(myDate.getFullYear()); // 获取完整的年份(4位,1970-????) console.log(myDate.getMonth()); // 获取当前月份(0-11,0代表1月) console.log(myDate.getDate()); // 获取当前日(1-31) console.log(myDate.getDay()); // 获取当前星期X(0-6,0代表星期天) console.log(myDate.getTime()); // 获取当前时间(从1970.1.1开始的毫秒数) console.log(myDate.getHours()); // 获取当前小时数(0-23) console.log(myDate.getMinutes()); // 获取当前分钟数(0-59) console.log(myDate.getSeconds()); // 获取当前秒数(0-59) console.log(myDate.getMilliseconds()); // 获取当前毫秒数(0-999) console.log(myDate.toLocaleDateString()); // 获取当前日期(年/月/日) console.log(myDate.toLocaleTimeString()); // 获取当前时间(时/分/秒) console.log(myDate.toLocaleString()); // 获取当前时间(年/月/日 时/分/秒) console.log(myDate.format("yyyy年MM月dd日 hh时mm分ss秒")); // 时间格式转换 })
二、结果展示
三、知识拓展
// 获取当前时间前一天 var date = new Date(); date.setDate(date.getDate - 1); // 前一天 var lastDate = date.format("yyyy-MM-dd"); // 获取当前时间前一月 var date = new Date(); date.setMonth(date.getMonth - 1); var lastMonth = date.format("yyyy-MM-dd"); // 获取当前时间前一年 var date = new Date(); date.setFullYear(date.getFullYear - 1); var lastYear = date.format("yyyy-MM-dd");
相关文章推荐
- JavaScript 比较两个日期大小 及格式化时间函数 java获取当前日期前几天或后几天
- JavaScript:获取系统当前时间,构造格式化的字符串
- 获取当前日期时间并格式化 - 常见格式
- Javascript获取当前时间函数和时间操作小结
- javascript获取当前日期时间及其一些操作
- JS、javascript获取当前时间戳的方法
- java8获取当前时间并格式化
- JavaScript 获取当前毫秒时间戳
- JS获取当前时间并格式化"yyyy-MM-dd HH:mm:ss"
- java 时间 格式化(获取当前时间)
- mysql 获取当前日期函数及时间格式化参数详解
- c#获取当前日期时间以及格式化操作
- JavaScript格式化当前时间为yyyy-mm-dd形式
- javascript获取系统当前时间
- JavaScript简单获取系统当前时间完整示例
- Js获取当前日期时间及格式化操作
- js获取当前时间并格式化
- javascript获取当前时间CurentTime
- javascript获取当前日期时间和其它操作
- Js获取当前日期时间及格式化操作