2015-10-16 71 views
-1

有谁知道为什么我的日历对象不断打印3月份作为月份和1年份?有没有办法将日历设置为当前的月份和日期?日历对象不断打印3月份作为月份和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); 
    } 

} 
+4

什么是'得到月(...)'?如果你使用'Calendar',你需要使用像'calendar.get(Calendar.MONTH)'和'calendar.get(Calendar.YEAR)''的代码。如果您使用的是Java 8,则不应该使用'Calendar',而应该使用['LocalDate'](http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html )。 –

+0

@Rachel请在发布之前删除您的代码,以显示您的问题所需的[绝对最小值](http://stackoverflow.com/help/mcve)。 JavaFX的东西与您对日期时间的问题无关。 –

回答

0

java.time

顺便说一句,这样的工作是在java.time框架现在内置的Java 8和更高版本要容易得多。这些新类取代了已证明非常麻烦的旧java.util.Date/.Calendar类。

确定今天的日期。

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

使用某种格式生成该日期对象的字符串表示形式。

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

更好的是,生成本地化格式的字符串表示。

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日:10,2015年其在本地化的格式是:samedi 17 OCTOBRE 2015年

+0

这正是我需要的!我正在使用Java 8,所以Calendar和Date类没有做我所需要的。 – Rachel

+0

另一个问题,有没有办法找出本月开始的一周中的哪一天?例如,2015年10月的答案将是星期四,因为10月1日星期四开始。 – Rachel

+0

@Rachel评论是不是有其他问题的地方。首先搜索StackOverflow,看看你的新问题是否已经发布(它有*,*倍*倍)。如果还没有问,请发新问题。 –

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

的Calendar.get方法使用INT常数,以获得特定月/年场。 记住那个月是我相信从0开始计算的。

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

0

编辑给予更多的解释:

获取和日历对象上设置的方法将期望场数/职位,返回值,而且这些号码被定义为常量,比如月,年,日,DAY_OF_MONTH

所以,当你使用calendar.Month它只会返回你的字段数值而不是实际的月份。您需要使用get/set方法来获取日历实例中的实际值。

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

请添加一些解释。赋予基础逻辑比赋予代码更重要,因为它可以帮助OP和其他读者自己解决这个问题和类似的问题。 –