前幾天參加cvte的筆試,碰到了這樣一道題目:
//請寫乙個時間日期格式化的函式,具體要求如下:
function format(date,"yyyy-mm-dd hh-mm-ss") 輸出: 2016-09-06 15-28-21
function format(date,"yy/mm/dd hh:mm:ss") 輸出: 16/09/06/ 15:28:21
function format(date,"yyyy/mm/dd hh/mm/ss") 輸出: 2016/09/06/ 15/28/21
然後下面是我當時寫的答案:
functionformat(date,str);
mat.m=date.getmonth()+1;//月份記得加1
mat.h=date.gethours();
mat.s=date.getseconds();
mat.m=date.getminutes();
mat.y=date.getfullyear();
mat.d=date.getdate();
mat.d=date.getday();//
星期幾 mat.d=check(mat.d);
mat.h=check(mat.h);
mat.m=check(mat.m);
mat.d=check(mat.d);
mat.s=check(mat.s);
mat.m=check(mat.m);
console.log(
typeof
mat.d)
if(str.indexof(":")>-1)
if(str.indexof("/")>-1)
if(str.indexof("-")>-1)
}//檢查是不是兩位數字,不足補全
function
check(str)
return
str;
}
上面答案我是後來寫的,測試過了,沒有錯誤。但是原來我寫的答案存在以下幾個錯誤:
1、獲取的日期時間都是數字,不能直接用字串的方法,需要呼叫tostring先;
2、是indexof,中間的o要大寫。
如果只是這樣,其實我還可以接受啦,畢竟筆試的時候沒有除錯,只有你手寫。
但是,當我網上看到別人的**之後,我就不淡定了,高手就是不一樣,人家直接正則,搞定,哪像我還得乙個乙個if來判斷,效率低下,如果別人的樣式不是上面的幾種,就會出現一些問題。學習別人的方法的同時,順便複習下正則。
以下內容**zhangpengshou的部落格:
方法一:
//對date的擴充套件,將 date 轉化為指定格式的string
//月(m)、日(d)、小時(h)、分(m)、秒(s)、季度(q) 可以用 1-2 個佔位符,
//年(y)可以用 1-4 個佔位符,毫秒(s)只能用 1 個佔位符(是 1-3 位的數字)
//例子:
//(new date()).format("yyyy-mm-dd hh:mm:ss.s") ==> 2006-07-02 08:09:04.423
//(new date()).format("yyyy-m-d h:m:s.s") ==> 2006-7-2 8:9:4.18
date.prototype.format = function (fmt) ;
if (/(y+)/.test(fmt))
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;
}//呼叫:
var time1 = new date().format("yyyy-mm-dd");
var time2 = new date().format("yyyy-mm-dd hh:mm:ss");
方法二:
方法三:
date.prototype.format = function(mask)
return zeros +value;
};return mask.replace(/"[^"]*"|'[^']*'|/b ( ?: d |m | yy( ? : yy) ? | ([hhmstt]) / 1 ? | [llz]) / b / g, function ($0)
});};
js時間日期格式化
對date的擴充套件,將 date 轉化為指定格式的string 月 m 日 d 小時 h 分 m 秒 s 季度 q 可以用 1 2 個佔位符,年 y 可以用 1 4 個佔位符,毫秒 s 只能用 1 個佔位符 是 1 3 位的數字 例子 new date format yyyy mm dd hh m...
時間 日期格式化技巧
實際應用中,經常需要,2016 09 09 這種格式的字串日期格式 轉換方式 1.在生產日期格式時,在個位數字前補零,例如一些日期的js外掛程式。2.在拿到資料後,後台統一處理。後台格式化處理 函式 sprintf 資料格式,資料 資料格式 返回百分比符號 b 二進位制數 c 依照 ascii 值的...
php時間日期格式化
今天開始 begintoday date y m d 00 00 00 time 今天結束 endtoday date y m d 23 59 59 time 昨天開始 beginyesterday date y m d 00 00 00 strtotime 1 day 昨天結束 endyester...