JS实现日期格式化

日期处理类库:moment.js
Date.prototype.formatDate = function(format) {

		/** build on moment.js **/
		format = format || 'YYYY-MM-DD hh:mm:ss';
		return moment(this, format);
		/**
		 * 
		 * 
		var d = this;

		var zero = function(value) {
			return value < 10 ? "0" + value : value;
		}

		return format
				.replace(
						/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g,
						function($0) {
							switch ($0) {

							case 'd':
								return d.getDate();

							case 'dd':
								return zero(d.getDate());

							case 'ddd':
								return $.i18n.shortDays[d.getDay()];

							case 'dddd':
								return $.i18n.days[d.getDay()];

							case 'M':
								return d.getMonth() + 1;

							case 'MM':
								return zero(d.getMonth() + 1);

							case 'MMM':
								return $.i18n.shortMonths[d.getMonth()];

							case 'MMMM':
								return $.i18n.months[d.getMonth()];

							case 'yy':
								return ('' + d.getFullYear()).substr(2);

							case 'yyyy':
								return d.getFullYear();

							case 'h':
								return d.getHours() % 12 || 12;

							case 'hh':
								return zero(d.getHours() % 12 || 12);

							case 'H':
								return d.getHours();

							case 'HH':
								return zero(d.getHours());

							case 'm':
								return d.getMinutes();

							case 'mm':
								return zero(d.getMinutes());

							case 's':
								return d.getSeconds();

							case 'ss':
								return zero(d.getSeconds());

							case 'l':
								return zero(d.getMilliseconds(), 3);

							case 'L':
								var m = d.getMilliseconds();

								if (m > 99)
									m = Math.round(m / 10);

								return zero(m);

							case 'tt':
								return d.getHours() < 12 ? 'am' : 'pm';

							case 'TT':
								return d.getHours() < 12 ? 'AM' : 'PM';

							case 'Z':
								return d.toUTCString().match(/[A-Z]+$/);

								// Return quoted strings with the surrounding quotes removed     
							default:
								return $0.substr(1, $0.length - 2);

							}

						});
		 * **/

	};

 
 

你可能感兴趣的:(日期格式化)