5

このコードが 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

4 に答える 4

15

Calendar.YEAR, Calendar.MONTH,Calendar.DAY_OF_MONTHint定数です ( API docを参照してください)...

したがって、@Alex が投稿したStringように、Calendarインスタンスからフォーマットされたものを作成するには、SimpleDateFormat を使用する必要があります。

ただし、特定のフィールドの数値表現が必要な場合は、次のget(int)関数を使用します。

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

警告!月は0から始まります!!! これのせいで私はいくつかの間違いを犯しました!

于 2012-10-25T18:10:26.637 に答える
12

使用するSimpleDateFormat

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

メソッドで使用する定数を使用していCalendar.get()ます。

于 2012-10-25T18:10:25.437 に答える
2

なぜ使用しないのSimpleDateFormatですか?

public static String getNowDate() {
  return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}
于 2012-10-25T18:12:11.370 に答える
0

それは間違っている。への変更:

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));
于 2012-10-25T18:15:33.343 に答える