0

i have this code:

String start = startBox.getText();
String finish = finishBox.getText();

myprogram.addPeriod(start, finish)

addPeriod method has 2 GregorianCalendar as parameters, so how to convert the 2 string into GregorianCalendar?

I tried a couple of ways that i read on this site but they don't work with me

startBox and finishBox are 2 JTextField filled with date in this format: YYYY/MM/DD.

smartmouse
  • 13,912
  • 34
  • 100
  • 166
  • Welcome to Stack Overflow. Please read the [About] page. It may be obvious to you, but it is not necessarily obvious to people reading your question — which language are you using? — Oh, thank you for adding the Java tag (while I was typing). That will get your question to the right people. – Jonathan Leffler Jan 29 '14 at 17:50
  • I think you want to look at the `SimpleDateFormater`, convert to a date, and use that date to build your Calendar. – CodeChimp Jan 29 '14 at 17:52
  • Before posting, search for similar questions. This topic has been asked and answered many times on StackOverflow. For example, from almost 4 years ago: [Convert a string to a GregorianCalendar](http://stackoverflow.com/q/2331513/642706). Or [this one](http://stackoverflow.com/q/240510/642706). – Basil Bourque Jan 30 '14 at 00:21

1 Answers1

2

How about this, the steps are self-explanatory but you want to have a handle on an instance of SimpleDateFormat of the pattern in which you have your date.

Parse your Strings to get a Date instance and set your specific date to the respective Calendar instances.

try {

    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

    String start = startBox.getText();
    String finish = finishBox.getText();

    GregorianCalendar cal1 = new GregorianCalendar();
    cal1.setTime(format.parse(start));

    GregorianCalendar cal2 = new GregorianCalendar();
    cal1.setTime(format.parse(finish));

    myprogram.addPeriod(cal1, cal2);
}
} catch (ParseException e) {
    e.printStackTrace();
}
StoopidDonut
  • 8,547
  • 2
  • 33
  • 51
  • The 5th and 7th row give me this error: "Unhandled exception type ParseException" and Eclipse suggests me to add try-catch block. I did it but the program doesn't work anyway... Any other solution? – smartmouse Jan 29 '14 at 18:53
  • @smartmouse either enclose all the lines above within the try block or remove the try catch altogether and eclipse would suggest to add throws declaration on the method. Pick that – StoopidDonut Jan 29 '14 at 21:46
  • @smartmouse Check the edited code, you can enclose the entire code within your try bock – StoopidDonut Jan 30 '14 at 08:32