Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Date handling 1

Status
Not open for further replies.

awingnut

Programmer
Joined
Feb 24, 2003
Messages
759
Location
US
Is there an easy way to validate that a string is a valid date format then convert that to a standard format regardless of teh input format?

For example: 1/22/1956 -> 1956-01-22

TIA.
 
You can use a javascript date object. The parser for it is pretty smart as far as supporting multiple date formats. One thing that really blows about it though - it doesn't support dates seperated by dashes like what SQL produces.

Here's a small and dirty code example that should get you started:
Code:
function blah(dateString) {
   [i][COLOR=grey]//change dashes to slashes in case date is being supplied from SQL[/color][/i]
   dateString = dateString.replace(/-/g, "/");
   [i][COLOR=grey]//convert the string to a date object[/color][/i]
   var dateObj = new Date(dateString);
   [i][COLOR=grey]//reconvert the date to a standard SQL format
   //complete with handy-dandy leading 0's[/color][/i]
   var newDateString = dateObj.getFullYear + "-" + ((dateObj.getMonth + 1 < 10) ? "0" + (dateObj.getMonth + 1) : dateObj.getMonth) + "-" + ((dateObj.getDate < 10) ? "0" + dateObj.getDate : dateObj.getDate);
   return newDateString;
}

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
I guess I did my copy and paste wrong. When I do an 'alert(newDateString)' the following is displayed:
Code:
function getFullYear() {
   [native code]
}
-
function getMonth() {
   [native code]
}
-
function getDate() {
   [native code]
}
[\code]
Weird.
 
Never mind, I found the problem. The functions must have '()' on the end.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top