有 Java 编程相关的问题?

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

java日历返回错误的当前日期安卓

为什么此代码返回0001-02-05

public static String getNowDate() throws ParseException
{        
    return Myformat(toFormattedDateString(Calendar.getInstance()));
}

我将代码更改为:

public static String getNowDate() throws ParseException
{        
    Calendar temp=Calendar.getInstance();
    return temp.YEAR+"-"+temp.MONTH+"-"+temp.DAY_OF_MONTH;
}

现在它返回1-2-5

请帮我弄清楚实际日期。我只需要Sdk日期


共 (4) 个答案

  1. # 1 楼答案

    使用^{}

    new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
    

    您使用的常量将与Calendar.get()方法一起使用

  2. # 2 楼答案

    Calendar.YEARCalendar.MONTHCalendar.DAY_OF_MONTHint常数(只需在API doc中查找即可)

    因此,正如@Alex发布的那样,要从Calendar实例中创建格式化的String,应该使用SimpleDataFormat

    但是,如果需要特定字段的数字表示,请使用get(int)函数:

    int year = temp.get(Calendar.YEAR);
    int month = temp.get(Calendar.MONTH);
    int dayOfMonth = temp.get(Calendar.DAY_OF_MONTH);
    

    警告月份从0开始!!!因为这个,我犯了一些错误

  3. # 3 楼答案

    为什么不使用SimpleDateFormat

    public static String getNowDate() {
      return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }
    
  4. # 4 楼答案

    你做错了。改为:

    return temp.get(Calendar.YEAR)+"-"+ (temp.get(Calendar.MONTH)+1) +"-"+temp.get(Calendar.DAY_OF_MONTH);
    

    此外,您可能希望了解Date

    Date dt = new Date();
    //this will get current date and time, guaranteed to nearest millisecond
    System.out.println(dt.toString());
    //you can format it as follows in your required format
    System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(dt));