如何让Java显示从日期开始的日期?

时间:2013-11-09 05:29:43

标签: java

我想提取今天的日期。我有这个

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
JOptionPane.showMessageDialog(null, date.getDay());

但是当显示消息对话框时,它会显示数字5 今天它是8。如何设置它以显示该月的哪一天?

4 个答案:

答案 0 :(得分:1)

date.getDay()返回星期几。周日是0,周六同样是6。

请参阅java docs

根据以下评论

Calendar cal = Calendar.getInstance();
    int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

    String dayOfMonthStr = String.valueOf(dayOfMonth);
    System.out.println(dayOfMonthStr);

答案 1 :(得分:0)

试试这个。

JOptionPane.showMessageDialog(null, date.getTime());

答案 2 :(得分:0)

您开始使用SimpleDateFormat类,但没有对它做任何事情。尝试:

System.out.println( new SimpleDateFormat("EEEE").format( new Date() ) );
System.out.println( new SimpleDateFormat("d").format( new Date() ) );

答案 3 :(得分:0)

TL;博士

LocalDate.now()             // Capture the current date as seen in the wall-clock time used by the people of a certain region, that region represented by the JVM’s current default time zone.
         .getDayOfMonth()   // Extract the day-of-month. Returns an `int`. 

java.time

  

提取今天日期的某一天

现代方法使用 java.time 类来取代与最早版本的Java捆绑在一起的麻烦的旧日期时间类。

LocalDate

LocalDate类表示没有时间且没有时区的仅限日期的值。

时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,在Paris France午夜后的几分钟是新的一天,而Montréal Québec中仍然是“昨天”。

如果未指定时区,则JVM会隐式应用其当前的默认时区。该默认值可能随时更改,因此您的结果可能会有所不同。最好明确指定您期望/预期的时区作为参数。

continent/region的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用诸如ESTIST之类的3-4字母缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

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

如果要使用JVM的当前默认时区,请求它并作为参数传递。如果省略,则隐式应用JVM的当前默认值。最好是明确的,因为默认情况下可以在运行时期间由JVM中任何应用程序的任何线程中的任何代码随时更改

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

询问its day-of-monthLocalDate

int dayOfMonth = today.getDayOfMonth() ;

关于 java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendar和& SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

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

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore


约达时间

更新:Joda-Time项目现在位于maintenance mode,团队建议迁移到java.time课程。我将此部分保留为历史。

在Java 7中的Joda-Time 2.3 ...

org.joda.time.DateTime theEighth = new org.joda.time.DateTime( 2013, 11, 8, 18, 0 ); // Default time zone.
System.out.println( "theEighth: " + theEighth );
System.out.println( "dayOfMonth of theEighth: " + theEighth.dayOfMonth().getAsText() );

跑步时......

theEighth: 2013-11-08T18:00:00.000-08:00
dayOfMonth of theEighth: 8