Confirm DateTime

Hi all,
I need to confirm a dateTime format such as “01-21-2010 11:06:51AM” in textbox, and datetime has to be valid.
Example: “01-35-2010 11:60:51AM” is not a valid dateTime.

Please let me know.Thank you all.

Look at the Date documentation. You can pass a string to the constructor and it will convert it to a timestamp (an integer). Unfortunately what you’re testing won’t be accepted by the Date.parse method.

You will need to do some simple string manipulation. For example:

alert(new Date('01-21-2010 11:06:51AM')) // Invalid Date
alert(new Date('01 21 2010 11:06:51AM')) // Invalid Date
alert(new Date('01 21 2010 11:06:51')) // Works

So you need to do some simple string replacements (- for a space) and remove the AM/PM bit. You need to check if it was AM or PM. If it was PM, you then need to add 12 hours to the date object you get.

Thank you for the tips/ Do you have a sample to work with. I really dont have much time to implement this. Please guide me…Thank you.

You can use the slice method, where the endSlice parameter is used to remove the last two characters.

'01-35-2010 11:60:51AM'.slice(0, -2); // removes AM

It is easy to make a date- not so easy to validate date input.
Your input will work if you use Date.parse(s.replace(/[^\d:]+/g,’ '),
but so will january 35.

To a computer, january 35 is the same thing as february 4.
After you make the date you need to verify that the input matches the output.

For that it helps to be able to get and set arrays of date string parts.

function valid_date(daystring){
	var i= 0, ck, m, DA, TA, time;
	try{
		m=  /pm$/i.test(daystring);
		var DA= daystring.split(/\\D+/);
		DA.unshift(DA.splice(2, 1));
		while(i<6){
			DA[i]= parseInt(DA[i], 10);
			++i;
		}
		DA[1]-= 1;
		if(m) DA[3]+= 12;
		time= Date.fromArray(DA.slice(0, 6));
		TA= time.dateArray();
		i= 0;
		while(i<6){
			if(TA[i]!= DA[i]){
			    throw daystring+' is not a calendar date';
			}
			++i;
		}
		return time;
	}
	catch(er){
		throw 'Bad Date- '+daystring;
	}
}
Date.prototype.dateArray= function(){
	var D= this;
	return [D.getFullYear(), D.getMonth(), D.getDate(), D.getHours(),
	D.getMinutes(), D.getSeconds()];
}

Date.fromArray= function(A){
	var D= new Date();
	while(A.length<7) A.push(0);
	var T= A.splice(3, A.length);
	D.setFullYear.apply(D, A);
	D.setHours.apply(D, T);
	return D;
}

var s= ‘02-29-2010 11:50:51AM’; // bad date
var s1= ‘02-29-2012 11:50:51AM’; // good date
alert(valid_date(s))
alert(valid_date(s1))

You need a better date format, though.

This the above code throw this error:
Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; InfoPath.1; .NET CLR 2.0.50727; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)
Timestamp: Fri, 29 Jan 2010 16:30:59 UTC

Message: Exception thrown and not caught
Line: 32
Char: 2
Code: 0

I have built this but still doesnt work …any help apprecaited.


<script language="javascript">

function valid_date(daystring){

var x = daystring.slice(0, -2);
x = x.replace(/-/gi," ");
var a = Date.parse(x);

if(isNaN(a)){
alert(a+'\
No good');
}
	
if(daystring.indexOf("PM") >-1 || daystring.indexOf("pm")>-1){
//daystring.setHours(12);

}
}
</script

It’s a good start. The problem is that I misled you a bit by saying the constructor would return an integer, which is false. Date.parse returns an integer, but new Date() returns a Date object. So you need this:

function valid_date(daystring){

var x = daystring.slice(0, -2);
x = x.replace(/-/gi," ");
x = new Date(x);

if(isNaN(Date.parse(x))){ // check if the timestamp itself is a Number (if so, it was a valid date)
alert(x+'\
No good');
return false; // exit because it's a bad date
}
    
if(daystring.indexOf("PM") >-1 || daystring.indexOf("pm")>-1){
//daystring.setHours(12);

}
}

The setHours bit won’t work. It will just set the Hours component to 12. You want to add 12. So you need to use getHours, then add 12, then use setHours. Also, you need to do this before the Date.parse check.

I am getting this error:
Message: Object doesn’t support this property or method
Line: 14 -
z = daystring.getHours() + 12;
x.setHours(z);


function valid_date(daystring){ 
var x = daystring.slice(0, -2);
x = x.replace(/-/gi," ");
x = new Date(x);

if(daystring.indexOf("PM") >-1 || daystring.indexOf("pm")>-1){
z = daystring.getHours() + 12;
x.setHours(z);
}

if(isNaN(Date.parse(x))){

alert(x+'\
No good');
return false; // exit because it's a bad date
}

}

The Date object is x, not daystring.

You need to do x.getHours() to get the hours.

z = x.getHours() + 12;
alert(z); gives an “NaN” why??? it doesn work.

To find out why, one need to know what the function is being provided for the daystring variable.

i am lost… what do you mean?

You say that alert(z) says NAN

z ultimately comes from the daystring variable.

So, what is the value of daystring that makes the problem occur?

Basically you need to learn to debug each step of what you are doing, i.e. sprinkle your alerts all over the place to see where the problem is.

Please refer a short cut… i dont have much time.

Oh dear - I can’t dedicate time to this right now, so I guess I’m not getting paid.

When i alert(x.getHours()) = >13; the output already being converted to a military date hours for 12-05-2010 01:44:33pm. Means that there is no need to “pm” check section.

And this should be a bad date “02-29-2010 01:44:33AM” but system doesnt alert about it.

Either some of knows more or just trying to confuse me. and those who really help/guide thank you very much.

And pmw57, you dont have to help at all. Please dont respond any more.

pmw57 has a point. If time is a pressure, you have to pay someone to do it. We are offering our help during our free time, so impatience from you is something we are not prepared to put up with.

This forum is not a place for quick answers. It isn’t a place where you get your work done for you for free. You are here to seek help and to learn. Therefore this means one of the things we expect you to do is to try to debug your own code. If that’s challenging, you then need to do some research of your own, e.g. “how to debug javascript” in Google would be a good start.

Example:

function valid_date(daystring){ 
  var x = daystring.slice(0, -2);
  x = x.replace(/-/gi," ");
  x = new Date(x);

  if(daystring.indexOf("PM") >-1 || daystring.indexOf("pm")>-1){
    z = x.getHours() + 12;
    alert(z); // alerts 23
    x.setHours(z);
  }

  if(isNaN(Date.parse(x))) {
    alert(x+'\
No good');
    return false; // exit because it's a bad date
  }
  return true; // return true because it's a valid date
}

alert(valid_date('02-29-2012 11:50:51PM'));

I get “true” out of that.

It’s interesting that this is a valid date: 14-14-2004 41:84:93AM. Looks like JavaScript’s Date.parse() method is very forgiving. 14-14-2004 41:84:93AM actually becomes Tue Feb 15 2005 18:25:33

It simply adds a year if the number of months is over 12. Same for hours, minutes, seconds, days. If you want to make it more robust you’ll have to add code of your own.

This means you’ll have to do some different checks. Instead of replacing the dashes with spaces, use split() to split the string into a date and a time component. Then split() the date component (by dashes) into dd, mm, and yyyy components. Then check that each is a sensible number. Do the same for the time, split()ting it by the colon (:).

Also consider whether the person will use dd-mm-yyyy or mm-dd-yyyy. And what if people do dd/mm/yyyy or dd.mm.yyyy or dd mm yyyy? Same for time - hh.mm.ss?

If this is too much, you might be interested in something like this: http://www.datejs.com/

Personally, my approach would have been along the lines of using substr() or regex to extract each of the components of the date. Then feed them as args to Date.UTC(), and then create a Date object. Then, use the getUTC*() methods to retrieve the individual units again, and rebuild the string. Then compare to the original string.

If a value is out of range(eg day 35) then Date.UTC() will increment the month, and year etc… if necessary in order to normalize the values back to the correct ranges. That will net you a different string than the original, which is what you want.

You’ll need to massage it a bit, handling am/pm, and making the appropriate units start at 0 instead of 1.

I’m assuming “valid” is not dependant on timezone, or daylight savings time.