公历和日期格式 Java

GregorianCalendar and DateFormat Java

我正在尝试做一个简单的练习,在这个练习中我取一个日期,加上 90 天,然后将其格式化为如下格式:

Monday, April 20, 1998.

我将使用 GregorianCalendarDateFormat 来执行此操作。到目前为止,我有这个编译代码,但是我得到一个运行时错误,我无法将给定的 Object 格式化为 Date:

import java.util.*;
import java.text.*;

class Assignment21 {
    public static void main(String args[]) {
        GregorianCalendar ddate = new GregorianCalendar(1994, 10, 20);
        ddate.add(Calendar.DAY_OF_MONTH, 90);
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, MM dd, yyyy");
        String date = sdf.format(ddate);
    }
}

如何使用 DateFormat 正确输出预定义的 GregorianCalendar 日期?

您必须更正您的代码:

而不是

String date = sdf.format(ddate);

尝试:

String date = sdf.format(ddate.getTime());

tl;博士

LocalDate.of( 1994 , Month.OCTOBER , 20 )                  // Generate a date-only value, a `LocalDate` object, without time-of-day and without time zone.
.plusDays( 90 )                                            // Add a span of time. Using immutable objects, a new `LocalDate` object is instantiated, without altering the first.
.format(                                                   
    DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
                     .withLocale( Locale.US )
)

Wednesday, January 18, 1995

java.time

您使用的是麻烦的旧日期时间 类,现在已经过时,已被 java.time 类 取代。

LocalDate ld = LocalDate.of( 1994 , 10 , 20 ) ; // Sane numbering for year and month, unlike legacy classes. '1994' = 1994, and 10 = October.
LocalDate ldLater = ld.plusDays( 90 ) ;

或使用 Month 枚举。

LocalDate ld = LocalDate.of( 1994 , Month.OCTOBER , 20 ) ; 
LocalDate ldLater = ld.plusDays( 90 ) ;

让 java.time 自动为您本地化。

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( Locale.US ) ;
String output = ldLater.format( f ) ;

关于java.time

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.

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

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类.

java.time类从哪里获得?

  • Java SE 8, Java SE 9, Java SE 10,及以后
    • 内置。
    • 标准 Java API 的一部分,带有捆绑实施。
    • Java 9 添加了一些小功能和修复。
  • Java SE 6 and Java SE 7
  • Android
    • Android java.time 类.
    • 捆绑实施的更高版本
    • 对于较早的 Android (<26),ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See

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.