Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take 3 Integers, create a date

Tags:

java

date

integer

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.

like image 220
speak Avatar asked Jan 17 '23 12:01

speak


1 Answers

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);
like image 172
Óscar López Avatar answered Jan 25 '23 22:01

Óscar López