日历返回错误的当前日期Android



为什么此代码返回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日期。

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

因此,正如@Alex发布的那样,要在Calendar实例中创建一个格式化的String,您应该使用SimpleDateFormat。

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

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

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

使用SimpleDateFormat

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

您使用的是与Calendar.get()方法一起使用的常数。

为什么不使用 SimpleDateFormat

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

您做错了。更改为:

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

另外,您可能需要研究日期:

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));

最新更新