-2

From server, I am getting valid date for some values in object, But I don't know for which field I will get number and for which field I will get date.

I tried with this question and its answers, It was giving correct result for string and dates, but now It is treating number as date. Any other solution to avoid treating number as date?

This question is to parse the date in different format. And my question is about distinguishing between date and number string. And performing operations on only date strings.

I am getting date in yyyy-MM-ddThh:mm:ss+Z.

Community
  • 1
  • 1
Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65
  • 2
    What do you mean by "is a date?" Do you mean matches a particular format? Which format? Why not just use that answer with a switch on `typeof`? – Mike Samuel Aug 31 '15 at 13:02
  • 1
    If you get the value 2015, than it could be the number 2015 (integer) or the year 2015 and thus a date. You need some criteria to distinguish numbers from dates since they can be both under certain circumstances. – cezar Aug 31 '15 at 13:04
  • 1
    What is "GMT" format? GMT is a timezone, not a format. – deceze Aug 31 '15 at 13:05
  • possible duplicate of [javascript Date.parse](http://stackoverflow.com/questions/2587345/javascript-date-parse) – Rahul Tripathi Aug 31 '15 at 13:06
  • @cezar, Yes thats the problem, I can't distinguish between date and time, Sometime date is with time and for some keys it is without time. – Laxmikant Dange Aug 31 '15 at 13:09
  • @RahulTripathi, I already mentioned the reference, Please read question before flagging, It is not the parsing issue, is date or not issue. – Laxmikant Dange Aug 31 '15 at 13:10

1 Answers1

2

Got the solution

Instead of checking if it is date or not, I need to check first if it is number or not. If it is not number then only it can be a date.

Here is What I did and it worked.

var obj={
  key1:"2015-10-10T11:15:30+0530",
  key2:2015,
  key3:"Normal String"
}

function parseDate(dateStr){
  if(isNaN(dateStr)){ //Checked for numeric
    var dt=new Date(dateStr);
    if(isNaN(dt.getTime())){ //Checked for date
      return dateStr; //Return string if not date.
    }else{
      return dt; //Return date **Can do further operations here.
    }
  } else{
    return dateStr; //Return string as it is number
  }
}

console.log("key1 ",parseDate(obj.key1))
console.log("key2 ",parseDate(obj.key2))
console.log("key3 ",parseDate(obj.key3))
Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65