在开发中经常会用到时间格式化,有时候在网上搜索一大堆但不是自己想要的,自己总结一下,写一个时间格式化工具方便以后直接使用,欢迎大家来吐槽……
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 | /** * Created by linxins on 2016/6/16. */ if ( typeof linxins !== 'function' ) { var linxins = function (){}; } ( function (){ var _self = this .linxins; /** * 获取当前时间的格式化日期 * @param string Fmt eg:Y-m-d H:i:s * @param boolean hasZero eg:true|false * @returns {string} */ _self.dateFormat = function (Fmt, hasZero){ return timeFormat(Fmt, hasZero); } /** * 将时间戳格式化 * @param number timestamp eg:1465963958000 length:13 * @param string Fmt eg:Y-m-d H:i:s * @param boolean hasZero eg:true|false * @returns {string} */ _self.timestampFormat =www.90168.org function (timestamp, Fmt, hasZero){ return timeFormat(timestamp, Fmt, hasZero); } /** * 时间字符串转时间戳 * @param string dateStr eg:2016-06-16 16:15:59 * @returns {number} */ _self.dateStr2timestamp = function (dateStr){ return ( typeof dateStr === 'string' ) ? Date.parse( new Date(dateStr)) : Date.parse( new Date()); } /** * 将时间戳格式化 * @param number timestamp eg:1465963958000 length:13 * @param string Fmt eg:Y-m-d H:i:s * @param boolean hasZero eg:true|false * @returns {string} */ function timeFormat(timestamp, Fmt, hasZero){ var date = ( typeof timestamp != 'undefined' && timestamp != '' ) ? new Date(timestamp) : new Date(); var hasZero = ( typeof hasZero === 'boolean' ) ? hasZero : true ; var Y = date.getFullYear(); var m = (hasZero && date.getMonth()+1 < 10) ? '0' +(date.getMonth()+1) : date.getMonth()+1; var d = (hasZero && date.getDate() < 10) ? '0' +date.getDate() : date.getDate(); var H = (hasZero && date.getHours() < 10) ? '0' +date.getHours() : date.getHours(); var i = (hasZero && date.getMinutes() < 10) ? '0' +date.getMinutes() : date.getMinutes(); var s = (hasZero && date.getSeconds() < 10) ? '0' +date.getSeconds() : date.getSeconds(); var fomateTime = '' ; switch (Fmt){ case 'YmdHis' : fomateTime = Y+m+d+H+i+s; break ; case 'Y-m-d H:i:s' : fomateTime = Y+ '-' +m+ '-' +d+ ' ' +H+ ':' +i+ ':' +s; break ; case 'Y/m/d H:i:s' : fomateTime = Y+ '/' +m+ '/' +d+ ' ' +H+ ':' +i+ ':' +s; break ; case 'Y-m-d H:i' : fomateTime = Y+ '-' +m+ '-' +d+ ' ' +H+ ':' +i; break ; case 'Y-m-d H' : fomateTime = Y+ '-' +m+ '-' +d+ ' ' +H; break ; case 'Y-m-d' : fomateTime = Y+ '-' +m+ '-' +d; break ; case 'Ymd' : fomateTime = Y + m + d; break ; case 'H:i:s' : fomateTime = H+ ':' +i+ ':' +s; break ; default : fomateTime = Y+ '-' +m+ '-' +d+ ' ' +H+ ':' +i+ ':' +s; break ; } return fomateTime; } })(window); |
//测试datetimeUtil
console.log(linxins.dateFormat());//当前时间格式:2016-06-16 16:44:49
console.log(linxins.dateStr2timestamp('2016-06-15 12:12:38'));//1465963958000
console.log(linxins.timestampFormat(1465963958000, 'Y/m/d H:i:s', false));//