yl.dateUtil = {
/**
* y 年
* M 月
* d 日
* H 时 h 时(am/pm)
* m 分
* s 秒
* S 毫秒
* a 上午/下午(am/pm)
* setInterval(function(){
* input111.value = yl.dateUtil.dateStr(new Date(), "要一个给小于9的d数m字s前H面M加0返回字符串的方法yyyy");
* }, 1000);
*/
dateStr: function (date, str) {
if (!date instanceof Date) {
return str;
}
//match之后得到数组
//遍历数组,
//判断各个元素长度、内容,做对应替换
var reg = /yyyy|yy|MM|M|dd|d|HH|H|h|mm|m|ss|s|SSS|S|a/g;
var strArr = str.match(reg);
for (var i = 0, len = strArr.length; i < len; i++) {
//console.log(strArr[i]);
switch (strArr[i]) {
case "yyyy":
str = str.replace(/yyyy/, date.getFullYear());
break;
case "yy":
str = str.replace(/yy/, (date.getFullYear()+"").substr(2,2));
break;
case "MM":
str = str.replace(/MM/, this.getLe9Str(date.getMonth()+1));
break;
case "M":
str = str.replace(/M/, date.getMonth()+1);
break;
case "dd":
str = str.replace(/dd/, this.getLe9Str(date.getDate()));
break;
case "d":
str = str.replace(/d/, date.getDate());
break;
case "HH":
str = str.replace(/HH/, this.getLe9Str(date.getHours()));
break;
case "H":
str = str.replace(/H/, date.getHours());
break;
case "h":
var s = date.getHours();
str = str.replace(/h/, s > 12 ? s % 12 : s);
break;
case "mm":
str = str.replace(/mm/, this.getLe9Str(date.getMinutes()));
break;
case "m":
str = str.replace(/m/, date.getMinutes());
break;
case "ss":
str = str.replace(/ss/, this.getLe9Str(date.getSeconds()));
break;
case "s":
str = str.replace(/s/, date.getSeconds());
break;
case "SSS":
str = str.replace(/SSS/, this.getLe99Str(date.getMilliseconds()));
break;
case "S":
str = str.replace(/S/, date.getMilliseconds());
break;
case "a":
str = str.replace(/a/, date.getHours() > 12 ? "pm" : "am");
break;
}
}
//console.log(str);
return str;
},
strDate: function () {
},
//要一个给小于9的数字前面加0返回字符串的方法
getLe9Str: function (num) {
return num > 9 ? "" + num : "0" + num;
},
//小于100前面加00或者0
getLe99Str: function (num) {
if (num > 9 && num < 100) {
return "0"+num;
} else {
return this.getLe9Str(num);
}
}
};
调用
<body>
<input type="text" id="input111" style="500px;"/>
<script type="text/javascript" src="ylUtil.js"></script>
<script type="text/javascript">
var input111 = document.getElementById("input111");
setInterval(function(){
input111.value = yl.dateUtil.dateStr(new Date(), "a h:mm:ss`SSS~~~~yyyy年M月d日");
}, 1);
</script>
</body>
ps:
- 觉得js用
new Date("2013/08/01 11:20:00")
的方式还是挺好的。所以strDate
没写了。 dateStr
方法用到参数格式从java的simpleDateFormat里面取的。所以与它的是一致的。- 用来把个日期转成指定字符串个人觉得够用了,关于性能问题,欢迎各路大虾提点。
- http://www.cnblogs.com/nimeiz/p/3446292.html