有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个现有的计划,我必须纠正。它包含以下行:

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

但是Date类型中的getDate()已被弃用,因此我必须使用日历来更改它。我试过这个:

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

但这会导致以下错误:

Type mismatch: cannot convert from Date to int


共 (6) 个答案

  1. # 1 楼答案

    正如javadocs所建议的,使用日历。get(日历、月日)

  2. # 2 楼答案

    要获取当月的日期:

    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.

  3. # 3 楼答案

    还有一个很好的选择是像这样使用:

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

    它将打印当前日期

    如果你需要时间和日期,你可以使用:

    System.out.println(DateFormat.getDateTimeInstance().format(new Date()));
    
  4. # 4 楼答案

    函数将返回一个无法转换为int的日期对象。如果要将日期转换为整数,必须使用:

    int day = startDate.get(Calendar.DATE)
    
  5. # 5 楼答案

    Type mismatch: cannot convert from Date to int

    改变

      int day= startDate.getTime();
    

     Date dat= startDate.getTime();//return type Date
    
  6. # 6 楼答案

    如果你想在一个月内得到一天,请使用以下方法:

    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.