0

I'm trying to format the date as per requirement. Requirement is if two date consist different years then there should be different format and if month is different then different format. Here is code

final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSSX");
          Calendar cal = Calendar.getInstance();
          cal.setTime(sdf.parse("2018-01-16T00:07:00.000+05:30"));
          Calendar cal2 = Calendar.getInstance();
          cal2.setTime(sdf.parse("2018-03-18T00:07:00.000+05:30"));
          SimpleDateFormat simpleDateformat = new SimpleDateFormat("E DD MMMM YYYY");
          if(cal.get(Calendar.YEAR) != cal2.get(Calendar.YEAR)){
              stringBuilder.append(simpleDateformat.format(cal.getTime())).append(" - ").append(simpleDateformat.format(cal2.getTime()));
              System.out.println("formatis"+stringBuilder.toString());
          }
          if(cal.get(Calendar.MONTH) != cal2.get(Calendar.MONTH)){
              SimpleDateFormat diffMonthFormat = new SimpleDateFormat("E DD MMMM");
              StringBuilder strBuilder = new StringBuilder();
              strBuilder.append(diffMonthFormat.format(cal.getTime())).append(" - ").append(simpleDateformat.format(cal2.getTime()));
              System.out.println("formatis"+ strBuilder.toString());
          }

Problem is it's working fine for different years but when i'm comparing month then output is

Tue 16 January - Sun 77 March 2018

It's showing date as 77.

Can anyone help

user2142786
  • 1,484
  • 9
  • 41
  • 74
  • Shouldn't it be `diffMonthFormat.format(cal2.getTime())` on the second if? – LMC Feb 06 '18 at 14:07
  • No,because i want output as DAY DD MONTH - DAY DD MONTH YEAR format . Thats why i'm using simpleDateformat . – user2142786 Feb 06 '18 at 14:12
  • 1
    The `SimpleDateFormat` class is not only long outdated, it is also notoriously troublesome. I recommend you use [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) for your code instead. It is so much nicer to work with. And it parses your input format (ISO 8601) without any explicit formatter. – Ole V.V. Feb 06 '18 at 14:12
  • Possible duplicate of [How to format today's day with SimpleDateFormat?](https://stackoverflow.com/questions/44110668/how-to-format-todays-day-with-simpledateformat) – Ole V.V. Feb 06 '18 at 14:19
  • Possible duplicate of [Formatting a String date into a different format in Java](https://stackoverflow.com/questions/47886611/formatting-a-string-date-into-a-different-format-in-java) – Ole V.V. Feb 06 '18 at 14:22
  • 1
    Now we’re at it, possible duplicate of [“EEE MMM dd HH:mm:ss ZZZ yyyy” date format to java.sql.Date](https://stackoverflow.com/questions/43933597/eee-mmm-dd-hhmmss-zzz-yyyy-date-format-to-java-sql-date) – Ole V.V. Feb 06 '18 at 14:33

1 Answers1

2

Day-of-month versus Day-of-year

Formatting codes are case-sensitive.

Your use of DD uppercase in SimplDateFormat is incorrect, as it means day-of-year (1-365, or 1-366 in a Leap Year). You are getting 77 for a date in March that is the seventy-seventh day into the year, 77 of 365. Use dd lowercase instead.

Your bigger problem is using the outmoded terrible classes. Use java.time instead.

java.time

You are using troublesome obsolete classes, now supplanted by the java.time classes.

DateTimeFormatter

Define your pair of DateTimeFormatter objects for generating output. Note the use of Locale argument to specify the human language and cultural norms used in localizing. Use single d instead of dd if you do not want to force a padding zero for single-digit values.

DateTimeFormatter withoutYear = DateTimeFormatter.ofPattern( "EEE dd MMMM" , Locale.US ) ;
DateTimeFormatter withYear = DateTimeFormatter.ofPattern( "EEE dd MMMM uuuu" , Locale.US ) ;

OffsetDateTime

Parse input as a OffsetDateTime as it includes an offset-from-UTC but not a time zone.

Your input strings comply with standard ISO 8601 formatting, used by default in the java.time classes. So no need to specify formatting pattern.

OffsetDateTime odtA = OffsetDateTime.parse( "2018-01-16T00:07:00.000+05:30" ) ;
OffsetDateTime odtB = …

Year & Month

Test their year part via Year class. Ditto for Month enum.

if( Year.from( odtA ).equals( Year.from( odtB ) ) ) {
    // … Use `withoutYear` formatter.
} else if( Month.from( odtA ).equals( Month.from( odtB ) ) ) { // If different year but same month.
    // … Use `withYear` formatter.
} else {  // Else neither year nor month is the same.
    // …
}

Generate string

To generate a string, pass the formatter to the date-time’s format method.

String output = odtA.format( withoutYear ) ;  // Pass `DateTimeFormatter` to be used in generating a String representing this date-time object’s value.

By the way, there is also a YearMonth class if you are ever interested in year and month together.


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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154