javascript常用代码【格式化时间日期】
2023-09-14 09:13:55 时间
这周工作中,写了几个前端界面,页面中有个表格列字段是时间类型的,但是后端传递过来的时间是时间戳,所以需要在前端将其转换展示。
记录一下格式化日期代码,以后再遇见类似功能直接复制黏贴即可(其实是为了多点时间摸鱼):
(1) 日期格式化代码
/**
* 日期格式化函数<br/>
* 调用格式:需要使用日期对象调用
* <p> new Date().Format("yyyy/MM/dd HH:mm:ss"); </p>
* @param fmt 日期格式
* @returns {*} 返回格式化后的日期
* @constructor
*/
Date.prototype.Format = function (fmt) {
var object = {
"M+": this.getMonth() + 1, // 月
"d+": this.getDate(), // 日
"H+": this.getHours(), // 时
"m+": this.getMinutes(), // 分
"s+": this.getSeconds(), // 秒
"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
"S": this.getMilliseconds() // 毫秒
};
// 正则表达式
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var pattern in object) {
if (new RegExp("(" + pattern + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (object[pattern]) : (("00" + object[pattern]).substr(("" + object[pattern]).length)));
}
}
return fmt;
}
(2) 函数调用
使用一个Date对象去调用Format函数即可。
时间戳转换,如果是时间戳需要转换,则需要注意的是,时间戳是10位长度的,还是13位长度的,如果是10位长度的时间戳,那么就需要乘以1000后,在调用Format进行转换。
举例如下:
// 调用函数
// 年月日
var date1 = new Date().Format("yyyy/MM/dd")
console.log(date1)
// 年月日 时分秒 毫秒
var date2 = new Date().Format("yyyy/MM/dd HH:mm:ss.S")
console.log(date2)
// 年月日 时分秒 毫秒 季度
var date3 = new Date().Format("yyyy/MM/dd HH:mm:ss.S qq")
console.log(date3)
// 时间戳
var date4 = new Date(1609430400000).Format("yyyy/MM/dd HH:mm:ss.S qq")
console.log(date4)
代码运行结果如下:
相关文章
- Javascript构造函数与prototype
- 数据结构与算法JavaScript (五) 串(经典KMP算法)
- aaronyang的百度地图API之LBS云与.NET开发 Javascript API 2.0【把数据存到LBS云2/2】
- Javascript定时器学习笔记
- [Javascript] Safely Access a Property on a JavaScript Array with Optional Chaining
- [Javascript] Broadcaster + Operator + Listener pattern -- 5. Merge (Example)
- [Javascript] Hide Properties from Showing Up in "for ... in" Loops in JavaScript
- [Javascript] Conditionally spread entries to a JavaScript object
- [Javascript] Replicate JavaScript Constructor Inheritance with Simple Objects (OLOO)
- [Javascript] How to use JavaScript's String.replace
- JavaScript 日期联动选择器
- [Javascript] Natively Format JavaScript Dates and Times
- [Javascript] Hide Properties from Showing Up in "for ... in" Loops in JavaScript
- [Javascript] Run asynchronous functions in sequence using reduce
- [Javascript] Multiply Two Arrays over a Function in JavaScript
- [Javascript] Understanding the .constructor property on JavaScript Objects
- [Javascript] Link to Other Objects through the JavaScript Prototype Chain
- [Whole Web] [AngularJS + Grunt] Using ng-html2js to Convert Templates into JavaScript
- java和javascript日期校验和闰年问题分析和解决方案
- 浅谈JavaScript中的原型模式
- 【华为OD机试 2023】 优选核酸检测点(C++ Java JavaScript Python)
- python web py入门(37)- javascript的switch-case语句