what's the best way to accept a date input from a user? can i use Keyboard.readString, and somehow parse the string input as a date? if so, how?
Printable View
what's the best way to accept a date input from a user? can i use Keyboard.readString, and somehow parse the string input as a date? if so, how?
Use a java.util.GregorianCalendar to construct a java.util.Date from various components.
To get the components, read in a string (however you do that, Keyboard.readString sounds like some programming class) and use a java.util.StringTokenizer to seperate them, then use Integer.valueOf to get an int.
Just to add. Wether you end up using the GregorianCalendar class or Calendar.getInstance() these classes are not intended to present the fields in a form suitable to the end user. java.text.DateFormat would take care of that issue.
Argh, I knew there was something like DateFormat, but I couldn't find it in java.util...
You can try DateFormat.parse
Yeah that class seems to come in handy. At least for me. ;)
i cant seem to get a string to "parse" into a date...
String f = new String ("25/12/2000");
Date df = new Date(f);
no?
What is the result?
Date(java.lang.String) has been deprecatedQuote:
Posted by quipy
i cant seem to get a string to "parse" into a date...
String f = new String ("25/12/2000");
Date df = new Date(f);
no?
I really don't think that there is a way to parse a string into a date or construct a date object from a string. All approaches seem to lead to dead ends. :confused:
Code:public class DateExample{
public static void main(String[] args){
try{
// Date to String
Date today = new Date(); //current time and date
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
// Styles FULL LONG MEDIUM SHORT,DEFAULT
String d = df.format(today);
System.out.println(d);
/*
String to Date
Should be the same as Date(java.lang.String)
which is deprecated but no compiler warning
is generated
DateFormat df2 = DateFormat.getDateInstance();
Date jan = df2.parse("01/02/03");
System.out.println(jan);
*/
/*
parse(java.lang.String) in java.util.Date
has been deprecated
long date = Date.parse("01/02/03");
Date jandate = new Date(date);
System.out.println(jandate);
*/
}catch(Exception e){;}
}
}
Another dead end. :p
Code:import java.util.Date;
import java.util.StringTokenizer;
public class DateExample{
public static void main(String[] args){
try{
int counter = 0;
int[] i = new int[3];
String date = new String("01/02/03");
StringTokenizer st = new StringTokenizer(date, "/");
while(st.hasMoreTokens()){
i[counter++] = Integer.parseInteger(st.nextToken());
}
// Date(int,int,int) in java.util.Date has been deprecated
Date d = new Date(i[0],i[1],i[2]);
System.out.println(d);
}catch(Exception e){;}
}
}
The DateFormat approach should work.
The StringTokenizer approach can be combined with a GregorianCalendar or other Calendar subclass.