JS 時間轉換函數 字符串時間轉換毫秒(互轉)


字符串轉化為日期

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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM