JavaScript通过Date-Mask将日期转换成字符串的方法
本文实例讲述了JavaScript通过Date-Mask将日期转换成字符串的方法。分享给大家供大家参考。具体实现方法如下:
varMonthNames=["January","February","March","April","May","June","July","August","September","October","November","December"]; varDayNames=["Sunday","Monday","Tueday","Wednesday","Thursday", "Friday","Saturday"]; varShortMths=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", "Sep","Oct","Nov","Dec"]; varShortDays=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]; varStringToDate=function(sDate,sFormat,cutOff){ //Input:adatevalueasastring,it'sformatasastringe.g.'dd-mmm-yy' //Optional:acutoff(integer)for2digityears. //Ifno'd'appearsintheformatstringthenthe1stofthemonthisassumed. //Iftheyearis20andthecut-offis30thenthevaluewillbeconverted //to2020;iftheyearis40thenthiswillbeconvertedto1940. //Ifnocut-offissuppliedthen'20'willbepre-pendedtotheyear(YY). //Output:astringintheformat'YYYY/MM/DD'or'' //Willnotattempttoconvertcertaincombinationse.g.DMM,MDD,DDM,YYYYD. varsParsed,fndSingle; //sParsedwillbeconstructedintheformat'YYYY/MM/DD' sDate=sDate.toString().toUpperCase(); sFormat=sFormat.toUpperCase(); if(sFormat.search(/MMMM|MMM/)+1){//replaceMar/Marchwith03,etc. sDate=sDate.replace(newRegExp('('+ShortMths.join('|')+')[A-Z]*','gi'), function(m){ vari=ShortMths.indexOf(m.charAt(0).toUpperCase()+ m.substr(1,2).toLowerCase())+1; return((i<10)?"0"+i:""+i).toString(); }); sFormat=sFormat.replace(/MMMM|MMM/g,'MM'); } if(sFormat.search(/DDDD|DDD/)+1){//replaceTue/Tuesday,etc.with'' sDate=sDate.replace(newRegExp('('+ShortDays.join('|')+')[A-Z]*','gi'),''); sFormat=sFormat.replace(/DDDD|DDD/g,''); } sDate=sDate.replace(/(^|\D)(\d)(?=\D|$)/g,function($0,$1,$2){ //singledigits2with02 return$1+'0'+$2; }); sFormat=sFormat.replace(/(^|[^DMY])(D|M)(?=[^DMY]|$)/g,function($0,$1,$2){ return$1+$2+$2;//replaceDorMwithDDandMM }); //aretherestillsingleDsorMs? fndSingle=sFormat.search(/(^|[^D])D([^D]|$)|(^|[^M])M([^M]|$)/)+1; //donotattempttoparse,forexample,'DMM' if(fndSingle)return''; sFormat=sFormat.replace(/(^|[^Y])(YY)(?=[^Y]|$)/g,function($0,$1,$2,index){ vartempDate=sDate.substr(0,index+1); tempDate+=(cutOff)?((parseInt(sDate.substr(index+1,2),10)>cutOff)?'19':'20'):'20'; tempDate+=sDate.substr(index+1); sDate=tempDate; return$1+$2+$2; }); sParsed=('YYYY/MM/DD').replace(/YYYY|MM|DD/g,function(m){ return(sFormat.indexOf(m)+1)? sDate.substr(sFormat.indexOf(m),m.length):''; }); if(sParsed.charAt(0)=='/'){ //ifnoyearspecified,assumethecurrentyear sParsed=(newDate().getFullYear())+sParsed; } if(sParsed.charAt(sParsed.length-1)=='/'){ //ifnodate,assumethe1stofthemonth sParsed+='01'; } //shouldendupwith10characters.. return(sParsed.length==10)?sParsed:''; };
希望本文所述对大家的javascript程序设计有所帮助。