开发者

How to tell the difference between a time string and a non-time string

I need a function that can tell if a string is in a time format. Something along these lines:

var string1 = "Normal String",
    string2 = "12:00pm";


function timeOrString(str) {
   if (str == A TIME) {
      alert('this is a time');
   }
   else {
      alert('this is a normal string');
   }
}

timeOrString(string1);
timeOrString(string2);

It could be something as simple as telling whether there is a number in the str开发者_如何学Cing?


var string1 = "Normal String",
    string2 = "12:00 pm";


function timeOrString(str){
  if(new Date("1/1/1900 " + str) != "Invalid Date" && str){
    alert("this is a valid time string");
  }else{
    alert("this is not a valid time string");
  }
}

timeOrString(string1);
timeOrString(string2);

That's one way of doing it. It's messy but it'll work... most of the time. :P


There are several ways to do it... Some use Regular Expresions other value checks... Here are some examples:

http://javascript.internet.com/forms/val-time.html http://www.the-art-of-web.com/javascript/validate-date/ http://www.codeproject.com/KB/scripting/timevalidation.aspx

But my recomendation, depending on what you are trying to do, its not use a text box to request the time, but use a jquery plugin to make date and time selectable, and control the input format that way:

http://trentrichardson.com/examples/timepicker/


You can use instanceof and typeof operators

var theDay = new Date(1995, 11, 17); // Dec. 17, 1995
 if (theDay instanceof Date)
 {
  print("theDay is a Date object");
   // whatever else...
 }

var myString = new String();
var myDate = new Date();


    myString instanceof String; // returns true
    myString instanceof Object; // returns true
    myString instanceof Date;   // returns false
    myDate instanceof Date;     // returns true
    myDate instanceof Object;   // returns true
    myDate instanceof String;   // returns false

instanceof

typeof

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜