aspose file tools*
The moose likes Beginning Java and the fly likes parse date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "parse date" Watch "parse date" New topic
Author

parse date

Jackie Wang
Ranch Hand

Joined: Apr 18, 2002
Posts: 315
I got a question for the String:
if I got 3 text field.
YYYY MM DD
i don't know the user will put 07 as month or 7 as month.
how I can make sure i got the string in format of "20030701" and have error if the date is invalid?
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
This is one way to ensure your format is correct.
Error checking needs to be done earlier, i.e. if the textfield = "" or if the dates are going to be invalid e.g. 20030231, or 20031525.
I've substituted strings for textfields - just add in where necessary textfield.gettext()
Susilo Saja
Ranch Hand

Joined: May 27, 2003
Posts: 91
Hi Jackie,
>>>how I can make sure i got the string in format of "20030701"
You can get the length of the input, if it's not 8, then it's not the input you want.
>>>and have error if the date is invalid?
what do you mean with invalid here? invalid like 32 as the date? or 31 as the date in November? if this is the case, you can get the year(y1), month(m1), date(d1) from the input (could use substring), create a GregorianCalendar(g) with y1, m1, d1. Get the year(y2), month(m2), date(d2) from g. If (y1 != y2 || m1 != m2 || d1 != d2) then it's invalid.
The reason it could work like this because in Java, if you try to create November 31, it won't generate error, but it will create Dec 1
Does this answer your question?
Susilo Saja
Ranch Hand

Joined: May 27, 2003
Posts: 91
one more thing is, it might make it easier and less error-prone if you use a separator for the format, like "2002-03-25" or "2002/03/25" or "2002 03 25"
Jackie Wang
Ranch Hand

Joined: Apr 18, 2002
Posts: 315
hi Susilo,
thanks!
Actually I have 3 textbox. One is Maximum 4 character, 2nd one is 2 and the 3rd one is 2.
So i will still get the data if the user put 7 in the month field and i will start treat it as 07. So any suggestion?
Susilo Saja
Ranch Hand

Joined: May 27, 2003
Posts: 91
It's usually less complicated when you use 3 textbox instead of 1.
I'm not really sure of your question. Do you want to make it "07" if the input is "7" and leave it if it's already "07"? If this is the case, you can check for the length of the input, if it's 1, add "0" in front. If it's 2, do nothing.
String input = ...;
if (input.length() == 0) //user didn't fill it, so it's invalid;
else if (input.length() == 1) input = "0" + input;
Jackie Wang
Ranch Hand

Joined: Apr 18, 2002
Posts: 315
thx Susilo, that's what i need
appreciated that =)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: parse date