- Date.prototype.format = function (format) { //prototype 意思:原型 js中的处理都是根据原型来的,这里等于给Date对象加了一个方法,在后面实例后可以直接调用了
- 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()
- }
- var week=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
- if (/(y+)/.test(format)) {
- format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
- }
- if (/(w+)/.test(fmt)){
- fmt = fmt.replace(RegExp.$1, week[this.getDay()]);
- }
- 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;
- }
-
- Date.prototype.add = function (part, value) {
- value *= 1;
- if (isNaN(value)) {
- value = 0;
- }
- switch (part) {
- case "y":
- this.setFullYear(this.getFullYear() + value);
- break;
- case "m":
- this.setMonth(this.getMonth() + value);
- break;
- case "d":
- this.setDate(this.getDate() + value);
- break;
- case "h":
- this.setHours(this.getHours() + value);
- break;
- case "n":
- this.setMinutes(this.getMinutes() + value);
- break;
- case "s":
- this.setSeconds(this.getSeconds() + value);
- break;
- default:
-
- }
- }
用法:
- var start = new Date();
- start.add("d", -1);
- start.format(‘yyyy/MM/dd w‘);
- start.add("m", -1);
1、先实例Date对象,表示获取一个时间,可以指定
2、用add方法来对时间进行处理
3、用format方法来进行指定要返回的日期格式
关于js中的date处理
原文:http://www.cnblogs.com/ktbdream/p/7669668.html