I rummaged through the heaps of documentation and realized that it’s best to use Calendar to work with the date. But the following question arose: is it possible in JAVA to set the desired date directly without unnecessary conversions, something like myDate.set("28.12.2016"); well, or a comma?

Tell me which way to dig or throw examples (just for setting the date and extracting it).

PS I am writing a console application, the date is entered manually by the user.

  • And LocalDateTime is better for me =) docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html - Mikhail Kolomiets
  • Actually Date just has the same constructor Date (int year, int month, int day) - Mikhail Kolomiets
  • In java-8 added a new api for working with dates (java.time package). If you cannot use java-8 (eg android), look at the Joda Time library - zRrr
  • @zRrr now, starting from the Android N version, Java 8 is supported) - Kirill Stoianov

2 answers 2

As I understand it, the method you need here.

  Calendar calendar = Calendar.getInstance(); calendar.set(2016, 6, 10); 

To display the date, use SimpleDateFormat.

For example:

  SimpleDateFormat dayFormat = new SimpleDateFormat("EEE, d MMMM", Locale.getDefault()); String myString = dayFormat.format(calendar.getTime()); 

Set the desired pattern to display the date, in the example above, the result will be "Sun, June 12"

And when you enter from the user, nothing prevents you from minus the entered month by one unit.

Comment from @zRrr:

SimpleDateFormat can parse strings with dates, like this:

 Date date = new SimpleDateFormat( "dd.MM.yyyy" ).parse( "28.12.2016" ); 

and so it’s best to parse user input if the date format in the string is known.

  • Be careful. Months in the Calendar are counted from 0 (January), also set will not reset the time to 0 (this is all indicated in the documentation by reference). Numbers starting with 0 are treated as octal numbers (there will be no big trouble in the case of dates, just the code from 09 will not compile). - zRrr
  • Yes, of course, I agree with you, corrected in the answer. There was nothing about time in the question, naturally it is necessary to fold it as well, or use the set method (int, int, int, int, int, int) - Roman Novoselov
  • Yes, I read that the numbering of months comes from scratch, therefore December is 11 months. That is why the Calendar did not seem convenient to me in terms of use. If the user specifies the date of birth 08/01/1989, it will be a double mistake. - Bogdan
  • one
    @Bogdan Completed the answer with your answers. - Roman Novoselov
  • @zRrr thanks corrected the flaws, just rewrote without thinking the date from the tray - Roman Novoselov
 Calendar c = Calendar.getInstance(); c.set(year, month, day); //вводим дату SimpleDateFormat format1 = new SimpleDateFormat("MMMM dd yyyy", Locale.ENGLISH); String formatted = format1.format(c.getTime());