[JS]根据格式字符串分析日期(MM与自动匹配两位的09和一位的9),货币分析成浮点数
1 var sDate = '11/2/2005 10:24:59';
2 var sFormat = 'MM/dd/yyyy hh:mm:ss';
3
4 function getDateFromFormat(dateString,formatString){
5 var regDate = /\d+/g;
6 var regFormat = /[YyMmdHhSs]+/g;
7 var dateMatches = dateString.match(regDate);
8 var formatmatches = formatString.match(regFormat);
9 var date = new Date();
10 for(var i=0;i<dateMatches.length;i++){
11 switch(formatmatches[i].substring(0,1)){
12 case 'Y':
13 case 'y':
14 date.setFullYear(parseInt(dateMatches[i]));break;
15 case 'M':
16 date.setMonth(parseInt(dateMatches[i])-1);break;
17 case 'd':
18 date.setDate(parseInt(dateMatches[i]));break;
19 case 'H':
20 case 'h':
21 date.setHours(parseInt(dateMatches[i]));break;
22 case 'm':
23 date.setMinutes(parseInt(dateMatches[i]));break;
24 case 's':
25 date.setSeconds(parseInt(dateMatches[i]));break;
26 }
27 }
28 return date;
29 }
30
31 function parseCurrency(currentString){
32 var regParser = /[\d\.]+/g;
33 var matches = currentString.match(regParser);
34 var result = '';
35 var dot = false;
36 for(var i=0;i<matches.length;i++){
37 var temp = matches[i];
38 if(temp =='.'){
39 if(dot) continue;
40 }
41 result += temp;
42 }
43 return parseFloat(result);
44 }
45 alert(getDateFromFormat(sDate,sFormat));
46 alert(parseCurrency("¥1,900,000.12"));
2 var sFormat = 'MM/dd/yyyy hh:mm:ss';
3
4 function getDateFromFormat(dateString,formatString){
5 var regDate = /\d+/g;
6 var regFormat = /[YyMmdHhSs]+/g;
7 var dateMatches = dateString.match(regDate);
8 var formatmatches = formatString.match(regFormat);
9 var date = new Date();
10 for(var i=0;i<dateMatches.length;i++){
11 switch(formatmatches[i].substring(0,1)){
12 case 'Y':
13 case 'y':
14 date.setFullYear(parseInt(dateMatches[i]));break;
15 case 'M':
16 date.setMonth(parseInt(dateMatches[i])-1);break;
17 case 'd':
18 date.setDate(parseInt(dateMatches[i]));break;
19 case 'H':
20 case 'h':
21 date.setHours(parseInt(dateMatches[i]));break;
22 case 'm':
23 date.setMinutes(parseInt(dateMatches[i]));break;
24 case 's':
25 date.setSeconds(parseInt(dateMatches[i]));break;
26 }
27 }
28 return date;
29 }
30
31 function parseCurrency(currentString){
32 var regParser = /[\d\.]+/g;
33 var matches = currentString.match(regParser);
34 var result = '';
35 var dot = false;
36 for(var i=0;i<matches.length;i++){
37 var temp = matches[i];
38 if(temp =='.'){
39 if(dot) continue;
40 }
41 result += temp;
42 }
43 return parseFloat(result);
44 }
45 alert(getDateFromFormat(sDate,sFormat));
46 alert(parseCurrency("¥1,900,000.12"));