Preface
I originally wanted to imitate the SimpleDateFormat() object in Java, but I felt it was inconvenient to use it, so I wrote it as a separate method.
Date format
2.1. Instructions
formatDate(date, fmt), where fmt supports the following formats:
- y (year)
- M (month)
- d (day)
- q (quarter)
- w (week)
- H (24 hours)
- h (12 hour hours)
- m (minutes)
- s (SEC)
- S (MS)
In addition, the number of characters determines the length of the output characters, such as yy output 16, yyyy output 2016, ww output Friday, www output Friday, etc.
2.2. code
The complete code consists of 30 lines:
/** * Format the date as a string of the specified format * @param date The date to be formatted, when not transmitted, defaults to the current time, or can be a timestamp * @param fmt Target string format, supported characters are: y,M,d,q,w,H,h,m,S, default: yyyy MM DD HH: mm: SS * @returns Returns the formatted date string */ function formatDate(date, fmt) { date = date == undefined ? new Date() : date; date = typeof date == 'number' ? new Date(date) : date; fmt = fmt || 'yyyy-MM-dd HH:mm:ss'; var obj = { 'y': date.getFullYear(), // Year, note that getFullYear must be used 'M': date.getMonth() + 1, // Month, notice from 0-11 'd': date.getDate(), // date 'q': Math.floor((date.getMonth() + 3) / 3), // quarter 'w': date.getDay(), // Week, notice it's 0-6 'H': date.getHours(), // 24 hour system 'h': date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, // 12 hour system 'm': date.getMinutes(), // Minute 's': date.getSeconds(), // second 'S': date.getMilliseconds() // Millisecond }; var week = ['day', 'One', 'Two', 'Three', 'Four', 'Five', 'Six']; for(var i in obj) { fmt = fmt.replace(new RegExp(i+'+', 'g'), function(m) { var val = obj[i] + ''; if(i == 'w') return (m.length > 2 ? 'week' : 'week') + week[val]; for(var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val; return m.length == 1 ? val : val.substring(val.length - m.length); }); } return fmt; }
2.3. Use examples
formatDate(); // 2016-09-02 13:17:13 formatDate(new Date(), 'yyyy-MM-dd'); // 2016-09-02 // September 2, 2016 Q3 Friday 13:19:15:792 formatDate(new Date(), 'yyyy-MM-dd The first q quarter www HH:mm:ss:SSS'); formatDate(1472793615764); // 2016-09-02 13:20:15
Date resolution
3.1. description
parseDate(str, fmt), where fmt supports the following formats:
- y (year)
- M (month)
- d (day)
- H (24 hours)
- h (12 hour hours)
- m (minutes)
- s (SEC)
- S (MS)
3.2. Complete code
The complete code consists of 17 lines:
/** * Parse string to date * @param str Date string entered, such as' 2014-09-13 ' * @param fmt String format, default 'yyyy m m d d', supports the following: y, m, D, H, m, s, s, w and q are not supported * @returns Date type date after resolution */ function parseDate(str, fmt) { fmt = fmt || 'yyyy-MM-dd'; var obj = {y: 0, M: 1, d: 0, H: 0, h: 0, m: 0, s: 0, S: 0}; fmt.replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g, function(m, $1, $2, $3, $4, idx, old) { str = str.replace(new RegExp($1+'(\\d{'+$2.length+'})'+$4), function(_m, _$1) { obj[$3] = parseInt(_$1); return ''; }); return ''; }); obj.M--; // Month starts from 0, so subtract 1 var date = new Date(obj.y, obj.M, obj.d, obj.H, obj.m, obj.s); if(obj.S !== 0) date.setMilliseconds(obj.S); // If milliseconds are set return date; }
3.3. Example code
parseDate('2016-08-11'); // Thu Aug 11 2016 00:00:00 GMT+0800 parseDate('2016-08-11 13:28:43', 'yyyy-MM-dd HH:mm:ss') // Thu Aug 11 2016 13:28:43 GMT+0800
Other date related methods
Others simply encapsulate several methods, which are simply posted here, including the following:
/** * ===================================== * Date related methods * ===================================== */ ;(function($) { $.extend( { /** * Format the date as a string in the specified format * @param date The date to be formatted, when not transmitted, defaults to the current time, or can be a timestamp * @param fmt Target string format, supported characters are: y,M,d,q,w,H,h,m,S, default: yyyy MM DD HH: mm: SS * @returns Returns the formatted date string */ formatDate: function(date, fmt) { date = date == undefined ? new Date() : date; date = typeof date == 'number' ? new Date(date) : date; fmt = fmt || 'yyyy-MM-dd HH:mm:ss'; var obj = { 'y': date.getFullYear(), // Year, note that getFullYear must be used 'M': date.getMonth() + 1, // Month, notice from 0-11 'd': date.getDate(), // date 'q': Math.floor((date.getMonth() + 3) / 3), // quarter 'w': date.getDay(), // Week, notice it's 0-6 'H': date.getHours(), // 24 hour system 'h': date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, // 12 hour system 'm': date.getMinutes(), // Minute 's': date.getSeconds(), // second 'S': date.getMilliseconds() // Millisecond }; var week = ['day', 'One', 'Two', 'Three', 'Four', 'Five', 'Six']; for(var i in obj) { fmt = fmt.replace(new RegExp(i+'+', 'g'), function(m) { var val = obj[i] + ''; if(i == 'w') return (m.length > 2 ? 'week' : 'week') + week[val]; for(var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val; return m.length == 1 ? val : val.substring(val.length - m.length); }); } return fmt; }, /** * Parse string to date * @param str Date string entered, such as' 2014-09-13 ' * @param fmt String format, default 'yyyy m m d d', supports the following: y, m, D, H, m, s, s, w and q are not supported * @returns Date type date after resolution */ parseDate: function(str, fmt) { fmt = fmt || 'yyyy-MM-dd'; var obj = {y: 0, M: 1, d: 0, H: 0, h: 0, m: 0, s: 0, S: 0}; fmt.replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g, function(m, $1, $2, $3, $4, idx, old) { str = str.replace(new RegExp($1+'(\\d{'+$2.length+'})'+$4), function(_m, _$1) { obj[$3] = parseInt(_$1); return ''; }); return ''; }); obj.M--; // Month starts from 0, so subtract 1 var date = new Date(obj.y, obj.M, obj.d, obj.H, obj.m, obj.s); if(obj.S !== 0) date.setMilliseconds(obj.S); // If milliseconds are set return date; }, /** * Format a date in a friendly format, for example, return "just" within 1 minute, * Return time of the day, return date of the year; otherwise, return date * @param {Object} date */ formatDateToFriendly: function(date) { date = date || new Date(); date = typeof date === 'number' ? new Date(date) : date; var now = new Date(); if((now.getTime() - date.getTime()) < 60*1000) return 'just'; // Within 1 minute as "just" var temp = this.formatDate(date, 'yyyy year M month d'); if(temp == this.formatDate(now, 'yyyy year M month d')) return this.formatDate(date, 'HH:mm'); if(date.getFullYear() == now.getFullYear()) return this.formatDate(date, 'M month d day'); return temp; }, /** * Convert a period of time to a friendly format, such as: * 147->"2 27 seconds. " * 1581->"26 21 seconds. " * 15818->"4 24 hours " * @param {Object} second */ formatDurationToFriendly: function(second) { if(second < 60) return second + 'second'; else if(second < 60*60) return (second-second%60)/60+'branch'+second%60+'second'; else if(second < 60*60*24) return (second-second%3600)/60/60+'hour'+Math.round(second%3600/60)+'branch'; return (second/60/60/24).toFixed(1)+'day'; }, /** * Convert time to MM:SS */ formatTimeToFriendly: function(second) { var m = Math.floor(second / 60); m = m < 10 ? ( '0' + m ) : m; var s = second % 60; s = s < 10 ? ( '0' + s ) : s; return m + ':' + s; }, /** * Determine whether a year is a leap year * @param year It can be a date type or an int type year without passing the default current time */ isLeapYear: function(year) { if(year === undefined) year = new Date(); if(year instanceof Date) year = year.getFullYear(); return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); }, /** * Get the total number of days in a month of a year. If there is no parameter, get the total number of days in the current month * Mode 1: $. getMonthDays(); * Method 2: $. getMonthDays(new Date()); * Mode 3: $. getMonthDays(2013, 12); */ getMonthDays: function(date, month) { var y, m; if(date == undefined) date = new Date(); if(date instanceof Date) { y = date.getFullYear(); m = date.getMonth(); } else if(typeof date == 'number') { y = date; m = month-1; } var days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // Number of days per month in a year that is not a leap year //If it's a leap year and it's February if(m == 1 && this.isLeapYear(y)) return days[m]+1; return days[m]; }, /** * Calculate the number of days between 2 dates by comparing the number of milliseconds * The Date passed in is either a Date type or a string Date in yyyy MM DD format * @param date1 Date 1 * @param date2 Date two */ countDays: function(date1, date2) { var fmt = 'yyyy-MM-dd'; // Converts a date to a string. The purpose of the conversion is to remove "hour, minute and second" if(date1 instanceof Date && date2 instanceof Date) { date1 = this.format(fmt, date1); date2 = this.format(fmt, date2); } if(typeof date1 === 'string' && typeof date2 === 'string') { date1 = this.parse(date1, fmt); date2 = this.parse(date2, fmt); return (date1.getTime() - date2.getTime()) / (1000*60*60*24); } else { console.error('Invalid parameter format!'); return 0; } } }); })(jQuery);
github: https://github.com/sxei
Blog Garden: http://www.cnblogs.com/liuxianan
copyright © 2012-2020 Xiaoming