Calendar对象将March打印为月份,将1打印为年份

时间:2015-10-16 15:01:41

标签: java date javafx calendar

有谁知道为什么我的日历对象会将March打印为月份,而将1打印为年份?有没有办法将日历设置为当前月份和日期?

import java.util.Date;
import java.util.GregorianCalendar;
import javafx.application.Application;

public class Calendar extends Application{
    @Override
    public void start(Stage stage) throws Exception {
    BorderPane pane = new BorderPane();

    // Create a calendar
    GregorianCalendar calendar = new GregorianCalendar();
    Date time = new Date();
    calendar.setTime(time);

    // Create title
    Text header = new Text(getMonth(calendar.MONTH) + ", " + calendar.YEAR);

    // place title in pane
    pane.setTop(header);
    BorderPane.setAlignment(header, Pos.CENTER);

    Scene scene = new Scene(pane);
    stage.setScene(scene);
    stage.show();
}

    public static void main(String[] args) {
        launch(args);
    }

}

3 个答案:

答案 0 :(得分:2)

Text header = new Text(getMonth(calendar.get(Calendar.MONTH)
        + ", " + calendar.get(Calendar.YEAR));

Calendar.get方法使用int常量来获取特定的MONTH / YEAR字段。 记住那个月我相信从0开始。

Java 8数据/时间类更好(虽然开头有点压倒性)。

答案 1 :(得分:0)

编辑以提供更多解释:

在Calendar对象上获取和设置方法将期望字段数/位置返回值,并且这些数字被定义为常量,如MONTH,YEAR,DAY,DAY_OF_MONTH等,

因此,当您使用calendar.Month时,它只会返回字段编号的值而不是实际的月份。您需要与get / set方法一起使用它来获取日历实例中的实际值。

示例

Text header = new Text(getMonth(calendar.get(Calendar.MONTH) + ", " + calendar.get(Calendar.YEAR));

答案 2 :(得分:0)

java.time

顺便说一下,现在构建到Java 8及更高版本的java.time框架中,这种工作要容易得多。这些新类取代了经证明非常麻烦的旧java.util.Date/.Calendar类。

确定今天的日期。

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
LocalDate today = LocalDate.now ( zoneId );

使用特定格式生成该日期对象的String表示。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "M, yyyy" );
String output = today.format ( formatter );

更好的是,以本地化格式生成String表示。

DateTimeFormatter formatterLocalized = DateTimeFormatter.ofLocalizedDate ( FormatStyle.FULL ).withLocale ( Locale.CANADA_FRENCH );
String outputLocalized = today.format ( formatterLocalized );

转储到控制台。

System.out.println ( "today: " + today + " is: " + output + " which in localized format is: " + outputLocalized );

跑步时。

  

今天:2015-10-17是:2015年10月,本地化格式为:samedi 17 octobre 2015