我正在尝试根据要求格式化日期。要求是如果两个日期包含不同的年份,那么应该有不同的格式,如果月份不同,那么不同的格式。 这是代码
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());
}
问题是它在不同年份工作正常但是当我比较月份时输出是
Tue 16 January - Sun 77 March 2018
它显示日期为77。
任何人都可以提供帮助
答案 0 :(得分:2)
格式代码区分大小写。
您在DD
中使用SimplDateFormat
大写不正确,因为它意味着每年的日期(1-365或1 -366闰年)。您将获得77
三月份的日期,即一年中的第七十七天,即365天中的77天。请改用小写dd
。
你更大的问题是使用过时的可怕课程。 改为使用 java.time 。
您正在使用麻烦的过时类,现在已被java.time类取代。
DateTimeFormatter
定义用于生成输出的DateTimeFormatter
对象对。请注意使用Locale
参数来指定本地化中使用的人类语言和文化规范。如果您不想为单位数值强制填充零,请使用单d
而不是dd
。
DateTimeFormatter withoutYear = DateTimeFormatter.ofPattern( "EEE dd MMMM" , Locale.US ) ;
DateTimeFormatter withYear = DateTimeFormatter.ofPattern( "EEE dd MMMM uuuu" , Locale.US ) ;
OffsetDateTime
将输入解析为OffsetDateTime
,因为它包含来自UTC的偏移但不包括时区。
您的输入字符串符合标准ISO 8601格式,默认情况下在java.time类中使用。所以不需要指定格式化模式。
OffsetDateTime odtA = OffsetDateTime.parse( "2018-01-16T00:07:00.000+05:30" ) ;
OffsetDateTime odtB = …
Year
& Month
通过Year
课程测试他们的年份部分。同上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.
// …
}
要生成字符串,请将格式化程序传递给日期时间的format
方法。
String output = odtA.format( withoutYear ) ; // Pass `DateTimeFormatter` to be used in generating a String representing this date-time object’s value.
顺便说一下,如果您对年份和月感兴趣,还有一个YearMonth
课程。
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.Date
,Calendar
和& SimpleDateFormat
现在位于Joda-Time的maintenance mode项目建议迁移到java.time类。
要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310。
从哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如Interval
,YearWeek
,YearQuarter
和more。