Skip to content

Instantly share code, notes, and snippets.

@SeriaWei
Last active July 17, 2017 07:57
Show Gist options
  • Save SeriaWei/d9a05da3f1e48f77de98168bf5491f8d to your computer and use it in GitHub Desktop.
Save SeriaWei/d9a05da3f1e48f77de98168bf5491f8d to your computer and use it in GitHub Desktop.
parse date with format
function parseDate(date,format) {
var year=0,month=0,day=0,hour=0,minute=0,seconds=0;
function toNumber(n){
if(n == ''){
return -1;
}
return Number(n);
}
function yearSetter(y,p){
if(y<1000){
y+=2000;
}else if(y<1899){
return false;
}
year = y;
return true;
}
function monthSetter(m,p){
if(m<1||m>12){
return false;
}
month = m-1;
return true;
}
function daySetter(d,p){
if(d<1||d>31){
return false;
}
day = d;
return true;
}
function hourSetter(h,p){
if(h<0||h>23){
return false;
}
hour=h;
return true;
}
function minuteSetter(m,p){
if(m<0||m>59){
return false;
}
minute=m;
return true;
}
function secondsSetter(s,p){
if(s<0||s>59){
return false;
}
seconds=s;
return true;
}
var setterMap = {
"y":yearSetter,
"yy":yearSetter,
"yyy":yearSetter,
"yyyy":yearSetter,
"M":monthSetter,
"MM":monthSetter,
"d":daySetter,
"dd":daySetter,
"h":hourSetter,
"hh":hourSetter,
"H":hourSetter,
"HH":hourSetter,
"m":minuteSetter,
"mm":minuteSetter,
"s":secondsSetter,
"ss":secondsSetter
};
var split='-';
var length = format.length;
for (var index = 0; index < length; index++) {
var element = format[index];
if(setterMap[element]) continue;
if(date.indexOf(element)>=0){
date=date.replace(element,split);
format=format.replace(element,split);
}
}
var formatArray = format.split(split);
var dateArray = date.split(split);
for(var i=0;i<formatArray.length;i++){
var part=formatArray[i];
if(!part) continue;
var setter = setterMap[part];
if(setter){
var num = toNumber(dateArray[i]);
if(num>=0){
if(setter(num,part)){
continue;
}
}
}
return null;
}
return new Date(year,month,day,hour,minute,seconds);
}
var f="dd-MM-yyyy hh:mm:ss";
var d="31-7-17 0:59:59";
var date = parseDate(d,f);
var y= date.getFullYear();
var m= date.getMonth();
var d= date.getDate();
var h= date.getHours();
var min= date.getMinutes();
var s= date.getSeconds();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment