web前端开发的小伙伴们在做一些接口调用的时候大部时候拿到的时间格式为时间戳毫秒数,使用起来比较头疼,我本人也是每次在做时间转换的时候都得自己写好一通代码,来计算时间的正确显示状态;今天也再此记录一下我本人目前使用时间转换代码,如果有需要用得着的小伙伴可以参考使用。
在使用之前首先得需要清楚JavaScript里的date对象属性的基本知识,我在此就不再赘述;如果有需要了解这部分知识的同学请自行查找JavaScript-date对象的相关文档进行知识补充;
为了使用方便提高使用效率,本人也是从方法封装的思路着手来解决此问题的,直接上代码:
(function($) {
$.extend({
myTime: {
/**
* 当前时间戳
* @return <int> unix时间戳(秒)
*/
CurTime: function() {
return Date.parse(new Date()) / 1000;
},
/**
* 时间戳转换日期
* @param <int> unixTime 待时间戳(秒)
* @param <bool> isFull 返回完整时间(年-月-日 或者 年-月-日 时:分:秒)
*/
UnixToDate: function(unixTime, isFull) {
var time = new Date(unixTime * 1);
var ymdhis = "";
ymdhis += time.getFullYear() + "-";
ymdhis += (time.getMonth() + 1) > 9 ? (time.getMonth() + 1) + "-" : "0" + (time.getMonth() + 1) + "-";
ymdhis += time.getDate() > 9 ? time.getDate() : "0" + time.getDate();
if (isFull === true) {
var ht = time.getHours();
if (ht < 10) {
ymdhis += " 0" + ht + ":";
} else {
ymdhis += " " + ht + ":";
}
if (time.getUTCMinutes() < 10) {
ymdhis += "0" + time.getUTCMinutes();
} else {
ymdhis += time.getUTCMinutes();
}
// ymdhis += time.getUTCSeconds();
}
return ymdhis;
}
}
});
})(jQuery);
调用方法:
$.myTime.UnixToDate(1610726400000, true) //"2021-01-16 00:00"
本文提供了一段用于将时间戳毫秒数转换为易读日期格式的JavaScript代码,并封装成jQuery插件,便于前端开发者快速使用。

9136

被折叠的 条评论
为什么被折叠?



