Share a js function toDate, jstodate that converts a string in the specified date format into a date.
Today, we found that the datetimebox of easyui could not display the date normally, and then we naturally realized the toDate function. After google, we did not find any satisfactory results, but all of them were quite cool. Write one by yourself. I thought that the js regular expressions can also be obtained by naming the group, but javascript does not seem to support it currently. The Code implemented now is as follows, hoping to help people who need it.
// By dragonimp 2015.5.3 // usage: // "9:10:10 ". toDate ("yyyy-M-d hh: mm: ss") // "2015/5/5 9:10:10 ". toDate ("yyyy/M/d hh: mm: ss") String. prototype. toDate = function (fmt) {if (fmt = null) fmt = 'yyyy-MM-dd hh: mm: ss'; var str = this; // fmt is the date format, and str is the date string var reg =/([yMdhmsS] +)/g; // The character var key in the date format = {}; var tmpkeys = fmt. match (reg); for (var I = 0; I <tmpkeys. length; I ++) {key [tmpkeys [I]. substr (0, 1)] = I + 1;} var r = str. match (fmt. replace (reg, "(\ d +)"); return new Date (r [key ["y"], r [key ["M"]-1, r [key ["d"], r [key ["h"], r [key ["m"], r [key ["s"], r [key ["S"]);}
Appendix: easyui problems and solutions.
Problem:
<Input type = "text" value = "2015/5/6 23:00:00" id = "xxxx" class = "easyui-datetimebox"/>
The displayed control, the "day" part of the date is displayed incorrectly, and the date of the day is displayed.
Check that easyui has referenced the Chinese resource file. After reading the resource file, it should only support the "-" split date. Here I am "/"
Solution: Implement formatter and parser by yourself.
1. Add options
<Input type = "text" value = "2015/5/6 23:00:00" id = "xxxx" class = "easyui-datetimebox" data-options = "formatter: datetimebox_format, parser: datetimebox_parse"/>
2. Implement parsing and formatting Functions
Function datetimebox_format (date) {return date. toFormatString ("yyyy/M/d h: mm: ss");} function datetimebox_parse (s) {return s. toDate ("yyyy/M/d hh: mm: ss");} // a) conversion date, see my previous toDate // B) Conversion string, from online Date. prototype. toFormatString = function (fmt) {var o = {"M +": this. getMonth () + 1, // month "d +": this. getDate (), // Day "h +": this. getHours (), // Hour "m +": this. getMinutes (), // minute "s +": this. getSeconds (), // second "q +": M Ath. floor (this. getMonth () + 3)/3), // quarter "S": this. getMilliseconds () // millisecond}; if (/(y + )/. test (fmt) fmt = fmt. replace (RegExp. $1, (this. getFullYear () + ""). substr (4-RegExp. $1. length); for (var k in o) if (new RegExp ("(" + k + ")"). test (fmt) fmt = fmt. replace (RegExp. $1, (RegExp. $1. length = 1 )? (O [k]): ("00" + o [k]). substr ("" + o [k]). length); return fmt ;}