如何从不推荐使用的日期类型中替换 getDate()?

How to replace getDate() from the type Date which is deprecated?

我有一个现有程序需要更正。它包含这些行:

        Date startDate = new Date();
        int day = startDate.getDate() - 1;

但是类型 Date 中的 getDate() 已弃用,因此我必须使用 Calender[= 进行更改22=]。我试过了:

Calendar startDate = Calendar.getInstance();
startDate.add(Calendar.DATE, -1);
int day= startDate.getTime();

但这会导致以下错误:

Type mismatch: cannot convert from Date to int

Type mismatch: cannot convert from Date to int

改变

  int day= startDate.getTime();

 Date dat= startDate.getTime();//return type Date

如果您想获取月中的某天,请使用以下命令:

int day= startDate.get(Calendar.DAY_OF_MONTH);

如果你想得到星期几,使用这个:

int day= startDate.get(Calendar.DAY_OF_WEEK);

还要注意星期几,因为第 0 天是星期日而不是星期一。

Field number for get and set indicating the day of the week. This field takes values SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.

正如 javadoc 所建议的那样,使用 Calendar.get(Calendar.DAY_OF_MONTH)

获取月份中的第几天:

int day= startDate.get(Calendar.DAY_OF_MONTH);

来自Javadocs

Field number for get and set indicating the day of the month. This is a synonym for DATE. The first day of the month has value 1.

getTime() 函数将 return 无法转换为 int 的日期对象。如果你想得到一个整数的天,你必须使用:

int day = startDate.get(Calendar.DATE)

参见 java 文档 http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getTime():

Date getTime() 方法的对象 return long 不在 int 中,所以使用 like:

long time = startDate.getTime();

对于 Calendar 文档 http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#getTime() 像下面这样使用:

long time = startDate.getTime().getTime();

一个月中的第几天:

Calendar c = Calendar.getInstance();
int dayOfMonth = c.get(Calendar.DATE);

在日期#startDate.getDate() returns 月份中的第几天:

  • 代码#1-->

    Date startDate = new Date();
    int day = startDate.getDate() - 1;
    System.out.println(day); 
    

通过 Calendar#.get(Calendar.DAY_OF_MONTH) 您将得到与 Date#startDate.getDate():

相同的结果
  • 代码#2-->

    Calendar startDate = Calendar.getInstance();
    int day= startDate.get(Calendar.DAY_OF_MONTH)-1;
    System.out.println(day);
    

因此您可以将代码#1 替换为代码#2

java.time

旧的 java.util.Date/.Calendar 类 是出了名的麻烦。它们已在 Java 8 及更高版本中被新的 java.time 框架所取代。

注意时区的使用。决定日期的关键。如果省略,则隐式依赖于 JVM 当前的默认时区。最好指定 desired/expected 时区。

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( zoneId );
int dayOfMonth = now.getDayOfMonth();
int dayOfWeek = now.getDayOfWeek().getValue();
int dayOfYear = now.getDayOfYear();

另一个不错的选择是使用 like :

System.out.println(DateFormat.getDateInstance().format(new Date()));

它将打印当前日期。

如果您需要时间和日期,那么您可以使用 like :

System.out.println(DateFormat.getDateTimeInstance().format(new Date()));

只需输入 int day = startDate.get(Calendar.DAY_OF_WEEK);