Add string transform date util function
Closed this issue · 7 comments
nightink commented
const utility = require('utility');
utility.str2date('20150412', 'yyyyMMdd'); // Date
help support util function
fengmk2 commented
do it
atian25 commented
以前写的一个:
/**
* format date.
*
* formatDate(new Date(),"yyyy-MM-dd hh:mm:ss")
* formatDate(new Date().setHours(0,0,0,0),"yyyy-MM-dd hh:mm:ss")
*
* 更建议用类库: [moment.js](http://momentjs.com/)
*
* @param {Date/Number} [obj] date to format, support Date or timestamp
* @param {String} [format] 格式
* @return {String} 格式化后的字符串
*/
Utils.formatDate = function(obj, format){
// iOS 时间格式化不一样
if(navigator.userAgent && navigator.userAgent.indexOf("NineGameClient/ios") > -1){
obj = (obj||'').replace(" ", "T");
}
var date = obj || new Date();
if(obj && obj.toString !== '[object Date]'){
if(isNaN(obj)){
date = new Date(obj);
}else{
date = new Date();
date.setTime(obj);
}
}
format = format || "yyyy-MM-dd hh:mm:ss";
var o = {
"M+" : date.getMonth()+1, //month
"d+" : date.getDate(), //day
"h+" : date.getHours(), //hour
"m+" : date.getMinutes(), //minute
"s+" : date.getSeconds(), //second
"q+" : Math.floor((date.getMonth()+3)/3), //quarter
"S" : date.getMilliseconds() //millisecond
};
if(/(y+)/.test(format)){
format=format.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o){
if(new RegExp("("+ k +")").test(format)){
format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
}
}
return format;
};
it('formatDate', function(){
var fn = Utils.formatDate;
expect(fn(new Date('2014-05-13 13:38:33'),"yyyy-MM-dd hh:mm:ss")).toEqual('2014-05-13 13:38:33');
expect(fn(new Date('2014-05-13 13:38:33'))).toEqual('2014-05-13 13:38:33');
expect(fn(new Date('2014-05-13 13:38:33'),"yyyy年MM月dd日")).toEqual('2014年05月13日');
expect(fn(new Date('2014-05-13 13:38:33').getTime(),"yyyy年MM月dd日")).toEqual('2014年05月13日');
});
hotoo commented
之前也将 univ 去 moment 写了个工具,也许有点用:
fengmk2 commented
哈哈,人手一个 utils
nightink commented
所以 utility 需要弄个简单点的~~ 😄😄
nightink commented
还是统一用 moment 吧。