Take 3 integers, create a date

I am trying to take 3 separate integer inputs (year, month, day) and take these 3 records and form a date object from them so that I can use it to compare other dates.

This is what I still did not understand 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); } 

Thanks so much for any help you can offer.

+4
source share
3 answers

Try this by noticing that the months start from zero, so we need to subtract them for the correct 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 that:

 Calendar calendar = Calendar.getInstance(); calendar.set(year, month-1, day); Date date = calendar.getTime(); 

Or that:

 Date date = new GregorianCalendar(year, month-1, day).getTime(); 

The first method gives you more control since it allows you to set other fields in the date, for example: DAY_OF_WEEK, DAY_OF_WEEK_IN_MONTH, DAY_OF_YEAR, WEEK_OF_MONTH, WEEK_OF_YEAR, MILLISECOND, MINUTE, HOUR, HOUR_OF_DAY

Finally, to properly format the date specified in the comments, do the following:

 DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); String strDate = df.format(date); 
+4
source

Use GregorianCalendar

 new GregorianCalendar(int year, int month, int dayOfMonth) 
+3
source

Please refer to this library, to another, to make your life easier in such a task - http://joda-time.sourceforge.net/

Then you write this code:

 LocalDate ld = new LocalDate(int year, int monthOfYear, int dayOfMonth) ; 

This class offers tons of useful methods for comparison and operations, such as adding minutes ... take a look at your documentation here

A bit more about joda-time:

Joda-Time provides a quality replacement for Java date and time classes. The design allows the use of several calendar systems, while providing a simple API. The default calendar is the ISO8601 standard that XML uses. Gregorian, Julian, Buddhist, Coptic, Ethiopian and Islamic systems are also included, and we welcome further additions. Supporting classes include time zone, duration, format, and parsing.

+2
source

Source: https://habr.com/ru/post/1415496/


All Articles