zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JS 时间转换函数 字符串时间转换毫秒(互转)

JS转换 函数 时间 字符串 互转 毫秒
2023-09-11 14:19:39 时间
字符串转化为日期

let util = function(){
Date.prototype.Format = function(fmt)
{
var o = {
"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 k in o)
if(new RegExp("("+ k +")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
return fmt;
};

return {
}
}();

日期转化为字符串

【1】js毫秒时间转换成日期时间


var oldTime = (new Date("2012/12/25 20:11:11")).getTime(); //得到毫秒数  


//不是上面格式的时间需要转换


   //starttime ='2012-12-25 20:17:24';
    starttime = starttime.replace(new RegExp("-","gm"),"/");
    var starttimeHaoMiao = (new Date(starttime)).getTime(); //得到毫秒数
2】毫秒数转化为时间


var oldTime = (new Date("2012/12/25 20:11:11")).getTime(); //得到毫秒数  
var newTime = new Date(oldTime); //就得到普通的时间了 

 

然后通过getHours,getFullYear等方法获取年月日,时分秒了

 

<script type="text/javascript">


var d = new Date()
document.write(d.getHours())
document.write(".")
document.write(d.getMinutes())
document.write(".")
document.write(d.getSeconds())

 

function timestampToTime(timestamp) {//转化成YYYYMMDDhhmmss格式的时间戳
    var date = new Date(timestamp),//时间戳为10位需*1000,时间戳为13位的话不需乘1000
    Y = date.getFullYear() + '',
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '',
    D = date.getDate() + '',
    h = date.getHours() + '',
    m = date.getMinutes() + '',
    s = date.getSeconds();
    return Y+M+D+h+m+s;
}