我正在尝试根据要求格式化日期。要求是,如果两个日期包含不同的年份,那么就应该有不同的格式,如果月份不同,则格式不同。这是代码
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。
有人能帮忙吗?
发布于 2018-02-06 20:57:25
月间日与年月日
格式化代码区分大小写.
您在DD SimplDateFormat 中使用大写是不正确的,因为它意味着一年一天(1-365,或跃年的1-366 )。你得到的是三月的77,那是一年中的第七十七天,365天中的77天。改用dd小写。
你更大的问题是使用过时的可怕的课程。使用 java.time 代替.
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
http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html框架内置到Java8和更高版本中。这些类取代了麻烦的旧遗赠日期时间类,如java.util.Date、Calendar和SimpleDateFormat。
http://www.joda.org/joda-time/项目现在在维护模式中,建议迁移到java.time类。
要了解更多信息,请参见http://docs.oracle.com/javase/tutorial/datetime/TOC.html。并搜索堆栈溢出以获得许多示例和解释。规范是JSR 310。
在哪里获得java.time类?
三次-额外项目使用其他类扩展java.time。这个项目是将来可能加入java.time的试验场。您可以在这里找到一些有用的类,如Interval、YearWeek、YearQuarter和更多。
https://stackoverflow.com/questions/48644797
复制相似问题