bhanu boyapati
bhanu boyapati

Reputation: 37

Mask formatter that accepts different types of date formats

I have to display a date in the format MM/dd/yyyy. The date to be displayed can be in any of the following formats

  1. MM/dd/yyyy
  2. MM/yyyy
  3. yyyy

If only month and year are available and day is not available then I have to display the date in the format MM/__/yyyy leaving the day blank.

If only year is available and day and month are not available then I have to display the date in the format __/__/yyyy leaving day and month blank.

I'm able to display it properly if whole date is available i.e. day, month and year using mask formatter. MaskFormatter formattedDate = new MaskFormatter("##'/##'/####"); but not able to display it if day or month is missing.

Is there any way to display the date leaving date and month blank?

Upvotes: 1

Views: 1068

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338181

java.time

The java.time classes built into Java 8 and later have a class for each of your needs:

  • LocalDate for date-only, without time-of-day, and without time zone.
  • YearMonth for a year and month but no date, and no time zone.
  • Year for just a year.

For example:

YearMonth ym = YearMonth.now( ZoneId.of( "Africa/Tunis" ) );

ym.toString(): 2018-02

All three offer a format method to which you pass a DateTimeFormatter object. You can define custom formatting patterns in that DateTimeFormatter. Search Stack Overflow as this has been covered many times already.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/__/uuuu" );
String output = ym.format( f );

02/__/2018

ISO 8601

By the way, consider using standard ISO 8601 formats to display these values as text. The format for a date is YYYY-MM-DD, and for a year-month, YYYY-MM.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Upvotes: 1

Related Questions