JavaScript開發經常需要對日期進行轉換,把日期轉成字符串或者從字符串生成日期。JavaScript日期對象內置了簡單的日期格式化方法toString()和日期解析方法Date.parse(),這兩個方法有較大的侷限性,不能自定義自定義日期格式化和解析的字符串格式。下面列出一些常用的日期處理JS庫。
名稱 | 描述 |
---|---|
Xdate | XDate對Javascirpt本地Date對象進行了輕度包裝,它提供對日期解析、格式化以及其他操作的加強功能,實現了本地Date對象的相同方法。 https://github.com/arshaw/xdate |
Moment.js | Moment.js是一個簡單易用的輕量級JavaScript日期處理類庫,提供了日期格式化、日期解析等功能。 https://github.com/moment/moment |
Date.js | Date.js是一個開源的JavaScript日期庫,用來解析、格式化和處理日期數據,支持多種語言的日期格式處理。Date.js官網已經不再更新,在github可以找到維護版 https://github.com/abritinthebay/datejs |
以上JS日期庫都提供了日期解析和格式化的功能,如果僅僅對日期實現格式化和解析,下面提供更輕量級的方法。
/**
* 日期格式化和解析
* DateUtils提供format和parse進行日期轉換。
* format(date, pattern)把日期格式化成字符串。
* 使用方法:
* var date = new Date();
* DateUtils.format(date, 'yyyy-MM-dd HH:mm:ss'); //2015-08-12 13:00:00
*
* parse(str, pattern)把字符串轉成日期。
* 使用方法:
* var str = 2015-08-12 13:00:00;
* DateUtils.format(str, 'yyyy-MM-dd HH:mm:ss');
*
* parse有兩個參數,如果只傳遞str參數,會調用瀏覽器內置的Date.parse()方法進行轉換。
*
* 格式 描述
* -------- ---------------------------------------------------------------
* yy 年份後兩位,如2015取後兩位是15。
* yyyy 年份四位。
* M 月份,取值1 ~ 12。
* MM 月份,取值01 ~ 12,如果月份爲個位數,前面補0。
* MMM 月份縮寫,如一月的英文縮寫爲Jan,中文縮寫爲一。
* MMMM 月份全稱,如January、一月。
* d 日期在月中的第幾天,取值1~31。
* dd 日期在月中的第幾天,取值01~31,如果天數爲個位數,前面補0。
* ddd 星期縮寫,取值日、一、二、三、四、五、六。
* dddd 星期全稱,取值星期日、星期一、星期二、星期三、星期四、星期五、星期六。
* H 24小時進制,取值0~23。
* HH 24小時進制,取值00~23,如果小時爲個位數,前面補0。
* h 12小時進制,取值0~11。
* hh 12小時進制,取值00~11,如果小時爲個位數,前面補0。
* m 分鐘,取值0~59。
* mm 分鐘,取值00~59,如果爲個位數,前面補0。
* s 秒,取值0~59。
* ss 秒,取值00~59,如果爲個位數,前面補0。
* S 毫秒,取值0~999。
* SS 毫秒,取值00~999,如果不足兩位數,前面補0。
* SSS 毫秒,取值000~999,如果不足三位數,前面補0。
* t 上午、下午縮寫。
* tt 上午、下午全稱。
* -------- ---------------------------------------------------------------
*
* @author [email protected]
* @date 2015-08-12
*/
DateUtils = (function(){
/*
var locale = {
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
shortDayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
shortMonthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
am: 'AM',
pm: 'PM',
shortAm: 'A',
shortPm: 'P'
};
*/
var locale = {
dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
shortDayNames: ["日", "一", "二", "三", "四", "五", "六"],
monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
shortMonthNames: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],
am: "上午",
pm: "下午",
shortAm: '上',
shortPm: '下'
};
/**
* 左邊補0
*/
function leftPad(str, size){
var result = '' + str;
while (result.length < size) {
result = '0' + result;
}
return result;
}
var parseToken = (function(){
var match2 = /\d{2}/, // 00 - 99
//match3 = /\d{3}/, // 000 - 999
match4 = /\d{4}/, // 0000 - 9999
match1to2 = /\d{1,2}/, // 0 - 99
match1to3 = /\d{1,3}/, // 0 - 999
//match1to4 = /\d{1,4}/, // 0 - 9999
match2w = /.{2}/, // 匹配兩個字符
match1wto2w = /.{1,2}/, // 匹配1~2個字符
map = {
//年的後兩位
'yy': {
regex: match2,
name: 'year'
},
//年
'yyyy': {
regex: match4,
name: 'year'
},
//兩位數的月,不到兩位數則補0
'MM': {
regex: match2,
name: 'month'
},
//月
'M': {
regex: match1to2,
name: 'month'
},
//兩位數的日期,不到兩位數則補0
'dd': {
regex: match2,
name: 'date'
},
//日期
'd': {
regex: match1to2,
name: 'date'
},
//兩位數的小時,24小時進制
'HH': {
regex: match2,
name: 'hours'
},
//小時,24小時進制
'H': {
regex: match1to2,
name: 'hours'
},
//兩位數的小時,12小時進制
'hh': {
regex: match2,
name: 'hours'
},
//小時,12小時進制
'h': {
regex: match1to2,
name: 'hours'
},
//兩位數的分鐘
'mm': {
regex: match2,
name: 'minutes'
},
//分鐘
'm': {
regex: match1to2,
name: 'minutes'
},
's': {
regex: match1to2,
name: 'seconds'
},
'ss': {
regex: match2,
name: 'seconds'
},
//上午、下午
'tt': {
regex: match2w,
name: 't'
},
//上午、下午
't': {
regex: match1wto2w,
name: 't'
},
//毫秒
'S': {
regex: match1to3,
name: 'millisecond'
},
//毫秒
'SS': {
regex: match1to3,
name: 'millisecond'
},
//毫秒
'SSS': {
regex: match1to3,
name: 'millisecond'
}
};
return function(token, str, dateObj){
var result, part = map[token];
if(part){
result = str.match(part.regex);
if(result){
dateObj[part.name] = result[0];
return result[0];
}
}
return null;
};
})();
return {
locale: locale,
format: function(val, pattern){
if(Object.prototype.toString.call(val) !== '[object Date]'){
return '';
}
if(Object.prototype.toString.call(pattern) !== '[object String]' || pattern === ''){
pattern = 'yyyy-MM-dd HH:mm:ss';
}
var fullYear = val.getFullYear(),
month = val.getMonth(),
day = val.getDay(),
date = val.getDate(),
hours = val.getHours(),
minutes = val.getMinutes(),
seconds = val.getSeconds(),
milliseconds = val.getMilliseconds();
return pattern.replace(/(\\)?(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|SS?S?)/g, function (m) {
if (m.charAt(0) === '\\') {
return m.replace('\\', '');
}
var locale = DateUtils.locale;
switch (m) {
case "hh":
return leftPad(hours < 13 ? (hours === 0 ? 12 : hours) : (hours - 12), 2);
case "h":
return hours < 13 ? (hours === 0 ? 12 : hours) : (hours - 12);
case "HH":
return leftPad(hours, 2);
case "H":
return hours;
case "mm":
return leftPad(minutes, 2);
case "m":
return minutes;
case "ss":
return leftPad(seconds, 2);
case "s":
return seconds;
case "yyyy":
return fullYear;
case "yy":
return (fullYear + '').substring(2);
case "dddd":
return locale.dayNames[day];
case "ddd":
return locale.shortDayNames[day];
case "dd":
return leftPad(date, 2);
case "d":
return date;
case "MMMM":
return locale.monthNames[month];
case "MMM":
return locale.shortMonthNames[month];
case "MM":
return leftPad(month + 1, 2);
case "M":
return month + 1;
case "t":
return hours < 12 ? locale.shortAm : locale.shortPm;
case "tt":
return hours < 12 ? locale.am : locale.pm;
case "S":
return milliseconds;
case "SS":
return leftPad(milliseconds, 2);
case "SSS":
return leftPad(milliseconds, 3);
default:
return m;
}
});
},
parse: function(val, pattern){
if(!val){
return null;
}
if(Object.prototype.toString.call(val) === '[object Date]'){
// 如果val是日期,則返回。
return val;
}
if(Object.prototype.toString.call(val) !== '[object String]'){
// 如果val不是字符串,則退出。
return null;
}
var time;
if(Object.prototype.toString.call(pattern) !== '[object String]' || pattern === ''){
// 如果fmt不是字符串或者是空字符串。
// 使用瀏覽器內置的日期解析
time = Date.parse(val);
if(isNaN(time)){
return null;
}
return new Date(time);
}
var i, token, tmpVal,
tokens = pattern.match(/(\\)?(dd?|MM?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|SS?S?|.)/g),
dateObj = {
year: 0,
month: 1,
date: 0,
hours: 0,
minutes: 0,
seconds: 0,
millisecond: 0
};
for(i = 0; i < tokens.length; i++){
token = tokens[i];
tmpVal = parseToken(token, val, dateObj);
if(tmpVal !== null){
if(val.length > tmpVal.length){
val = val.substring(tmpVal.length);
}else{
val = '';
}
}else{
val = val.substring(token.length);
}
}
if(dateObj.t){
if(DateUtils.locale.pm === dateObj.t || DateUtils.locale.shortPm === dateObj.t){
dateObj.hours = (+dateObj.hours) + 12;
}
}
dateObj.month -= 1;
return new Date(dateObj.year, dateObj.month, dateObj.date, dateObj.hours, dateObj.minutes, dateObj.seconds, dateObj.millisecond);
}
};
})();