Reputation: 5392
I am trying to take 3 separate integer inputs (year,month,day) and taking these 3 entries and forming an object of date from them so I can use it to compare other dates.
This is what I have so far, at a loss at where to go from here:
public void compareDates() {
String dayString = txtOrderDateDay.getText();
String monthString = txtOrderDateMonth.getText();
String yearString = txtOrderDateYear.getText();
int day = Integer.parseInt(dayString);
int month = Integer.parseInt(monthString);
int year = Integer.parseInt(yearString);
}
Many thanks for any help you have to offer.
Upvotes: 4
Views: 4345
Reputation: 236170
Try this, noticing that months start in zero so we need to subtract one to correctly specify a month:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month-1);
calendar.set(Calendar.DATE, day);
Date date = calendar.getTime();
Or this:
Calendar calendar = Calendar.getInstance();
calendar.set(year, month-1, day);
Date date = calendar.getTime();
Or this:
Date date = new GregorianCalendar(year, month-1, day).getTime();
The first method gives you more control, as it allows you to set other fields in the date, for instance: DAY_OF_WEEK, DAY_OF_WEEK_IN_MONTH, DAY_OF_YEAR, WEEK_OF_MONTH, WEEK_OF_YEAR, MILLISECOND, MINUTE, HOUR, HOUR_OF_DAY
etc.
Finally, for correctly formatting the date as indicated in the comments, do this:
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
String strDate = df.format(date);
Upvotes: 5
Reputation: 16599
Please refer to this library, in other to facilitate your life in such task - http://joda-time.sourceforge.net/
Then you are gonna write code like this:
LocalDate ld = new LocalDate(int year, int monthOfYear, int dayOfMonth) ;
This class offers a bunch of useful methods for comparison and operations like adding minutes... take a look at its documentation here
A bit more about joda-time:
Joda-Time provides a quality replacement for the Java date and time classes. The design allows for multiple calendar systems, while still providing a simple API. The 'default' calendar is the ISO8601 standard which is used by XML. The Gregorian, Julian, Buddhist, Coptic, Ethiopic and Islamic systems are also included, and we welcome further additions. Supporting classes include time zone, duration, format and parsing.
Upvotes: 2