Androidで現在の日付を取得するにはどうすればよいですか?


165

私は次のコードを書きました

Date d = new Date();
CharSequence s  = DateFormat.format("MMMM d, yyyy ", d.getTime());

しかし、パラメータを尋ねています。文字列形式の現在の日付が必要です。

お気に入り

28-Dec-2011

私が乗り越えられるようTextView

少し説明してください。何かが必要だと思われる場合、私はAndroid開発の初心者です。


1
DateFormatこの質問が2011年に尋ねられたとき、クラスの使用はSimpleDateFormat問題ありませんでしたが、そのクラスとそのサブクラスは常に面倒で、現在は古くなっています。それらを使用せずに、代わりに最新のJava日時APIであるjava.timeを調べることをお勧めします。
Ole VV

回答:


389

このSimpleDateFormatクラスを使用して、希望する形式で日付をフォーマットできます。

このリンクをチェックして、例のアイデアを見つけてください。

例えば:

String dateStr = "04/05/2010"; 
 
SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy"); 
Date dateObj = curFormater.parse(dateStr); 
SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy"); 
 
String newDateStr = postFormater.format(dateObj); 

更新:

詳細な例はこちらです。この例を読み、SimpleDateFormatクラスの概念を理解することをお勧めします。

最終的解決:

Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
String formattedDate = df.format(c);

代わりに、System.currentTimeMillis()メソッドまたはDataクラスをCalendarクラスの代わりに使用できます。より速くする必要があります。stackoverflow.com/questions/368094/...
cjayem13

これにはAPI 24が必要です!
ueen

以下のようなFYI、ひどく面倒日時クラスjava.util.Datejava.util.Calendarjava.text.SimpleDateFormat今のレガシーに取って代わられ、java.timeの Javaの8に、後に内蔵されたクラス。Oracleによるチュートリアル参照してください。
バジルブルク

@ueen androidからではなく、javaパッケージからインポートしてください。
サダフセイン

罰金ですか?現在?(2020年)
ルーククロス

152

このyyyy-MM-dd形式で現在の日付を取得するための簡単な1行のコードで、必要な形式を使用できます。

String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

7
次のように変更する必要があります。String currentDate = new SimpleDateFormat( "dd-MM-yyyy"、Locale.getDefault())。format(new Date());
Bart Burg 2014

1
わぁ、ありがとう!これはうまくいきましたが、おそらく仮想マシンの日付が正しくなかったために、仮想デバイスの日付が1日前に表示された理由がわかったと思います。実際の電話でテストしたところ、驚異的に機能しました。@Pratikにありがとう
wesley franks

30

あなたが使用できるようにJavaベースなので、これはAndroidとは関係ありません

private String getDateTime() { 
   DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
   Date date = new Date(); 
   return dateFormat.format(date); 
}

エラーが発生し、new Date()が引数を要求していて、SimpleDateFormatを使用してDateFormatを初期化していますが、これも無効です
Chatar Veer Suthar

12
 public String giveDate() {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy");
    return sdf.format(cal.getTime());
 }

11

これを試して、

SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
Date myDate = new Date();
String filename = timeStampFormat.format(myDate);

それは新しい日付に引数を追加することを言っている(長い)
Chatar Veer Suthar

new Date()では、長いパラメーターを要求できません。
Lucifer

プライベートキーワークを使用する理由、Androidプロジェクトでコードを実行する、出力を取得するのですか?
Chatar Veer Suthar、2011

その「プライベート」を削除してください。はい私は出力を取得します、私はあなたの議論を見ています。非常に単純な質問でなぜ問題が発生するのかわかりません。
Lucifer

7
CharSequence s  = DateFormat.getDateInstance().format("MMMM d, yyyy ");

最初にインスタンスが必要です


getDateInstance、これを認識しない
Veer Suthar

java docsを見ると、docs.oracle.com
javase/

@Veer、誤ってjava.text.DateFormatではなくandroid.text.format.DateFormatをインポートした場合、getDateInstance()は認識されません
gcbound

7

チャームのように機能し、ボーナスとして文字列に変換されます;)

SimpleDateFormat currentDate = new SimpleDateFormat("dd/MM/yyyy");
      Date todayDate = new Date();
    String thisDate = currentDate.format(todayDate);




4

私は現代の答えを提供しています。

java.timeとThreeTenABP

現在の日付を取得するには:

    LocalDate today = LocalDate.now(ZoneId.of("America/Hermosillo"));

これによりLocalDateオブジェクトが提供されます。これは、プログラムで日付を保持するために使用する必要があるものです。A LocalDateは時刻のない日付です。

ユーザーに日付を表​​示する必要がある場合のみ、ユーザーのロケールに適した文字列にフォーマットします。

    DateTimeFormatter userFormatter
            = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
    System.out.println(today.format(userFormatter));

今日、このスニペットを米国英語のロケールで実行すると、出力は次のようになります。

2019年7月13日

短くしたい場合は、FormatStyle.MEDIUMまたはを指定しますFormatStyle.SHORTDateTimeFormatter.ofLocalizedDateはデフォルトのフォーマットロケールを使用するため、重要なのは、ロケールごとに異なる、そのロケールに適した出力を提供することです。

ユーザーが出力フォーマットに対して非常に特別な要件を持っている場合は、フォーマットパターン文字列を使用します。

    DateTimeFormatter userFormatter = DateTimeFormatter.ofPattern(
            "d-MMM-u", Locale.forLanguageTag("ar-AE"));

13-يول-2019

最新のJava日時APIであるjava.timeを使用および推奨しています。DateFormatSimpleDateFormatDateCalendar疑問に使用される、および/または他の回答の多くは、設計が不十分と長い時代遅れされています。また、java.timeを使用する方がはるかに優れています。

質問:Androidでjava.timeを使用できますか?

はい、java.timeは古いAndroidデバイスと新しいAndroidデバイスでうまく動作します。少なくともJava 6が必要です。

  • Java 8以降および新しいAndroidデバイス(APIレベル26以降)では、最新のAPIが組み込まれています。
  • Java 6および7では、モダンクラスのバックポートであるThreeTenバックポートを取得します(JSR 310の場合はThreeTen。下部のリンクを参照)。
  • (古い)Androidでは、ThreeTenバックポートのAndroidエディションを使用します。これはThreeTenABPと呼ばれます。またorg.threeten.bp、サブパッケージを使用して日付と時刻のクラスをインポートしてください。

リンク集


とても良い答えです!しかし、どうすればThreeTen LocalDateTimeをDateに変換できますか?Firebaseを使用していますが、タイムスタンプを保存するための前提条件はDateオブジェクトです。
H.Karatsanov

バックポートを使用している場合H.Karatsanov @: DateTimeUtils.toDate(yourLocalDateTime.atZone(ZoneId.systemDefault()).toInstant())。内蔵のjava.timeを使用している場合:Date.from(yourLocalDateTime.atZone(ZoneId.systemDefault()).toInstant())java.time.LocalDateTimeとjava.util.Dateの間の変換を参照してください。JodaStephenによる信頼できる回答と、バックポートの使用を示す回答があります
Ole VV

4
 public static String getcurrentDateAndTime(){

        Date c = Calendar.getInstance().getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String formattedDate = simpleDateFormat.format(c);
        return formattedDate;
    }

// String currentdate=  getcurrentDateAndTime();

他の回答にまだない質問(私はのような文字列形式の現在の日付が欲しい)28-Dec-2011に大きく貢献していますか?いずれにせよ、それは悪名高い面倒で長く時代遅れのSimpleDateFormatクラスを使用しています。お願い、これ以上の答えは必要ありません。
Ole VV

ベストプラクティスで機能しています。2番目のパラメーターlocale SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy / MM / dd"、Locale.ENGLISH);を追加します。
Rucha Bhatt Joshi

3
Calendar cal = Calendar.getInstance();      
Calendar dt = Calendar.getInstance(); 
dt.clear();
dt.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),cal.get(Calendar.DATE)); 
return dt.getTime();        

3

Pareshのソリューションの簡単な調整:

Date date = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(date);

3
Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
String date = day + "/" + (month + 1) + "/" + year;

Log.i("TAG", "--->" + date);

2

次のコードを使用して、目的の形式で日付を取得できます。

String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));

素敵な1つのライナーと低いSDKで動作します。数文字短いDateFormat.format( "dd-MM-yyyy"、new java.util.Date())。toString()
Jeffrey

1
Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c);

これが一番の答えです...


0

現在のロケール(デバイスロケール!)で現在の日付を取得する最も簡単な方法:

String currentDate = DateFormat.getDateInstance().format(Calendar.getInstance().getTime());

異なるスタイルで日付を使用したい場合は、次のようにしますgetDateInstance(int style)

DateFormat.getDateInstance(DateFormat.FULL).format(Calendar.getInstance().getTime());

他のスタイル:DateFormat.LONGDateFormat.DATE_FIELDDateFormat.DAY_OF_YEAR_FIELD、など(使用CTRL+Spaceそれらのすべてを見るために)

あなたも時間が必要な場合:

String currentDateTime = DateFormat.getDateTimeInstance(DateFormat.DEFAULT,DateFormat.LONG).format(Calendar.getInstance().getTime());

0
  public static String getDateTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss", Locale.getDefault());
        Date date = new Date();
        return simpleDateFormat.format(date);
    }

0

このコードのリンクを試してみてください。これは、すべての場合において、日付と時刻を問わず、完全に正しい答えです。または、アプリのニーズと要件に従って日付と時刻をカスタマイズします。

このリンクで試してください。このリンクで試してください


0

CalendarViewを使用してカレンダーアプリを作成しました。これは私のコードです。

CalendarView cal = (CalendarView) findViewById(R.id.calendar);
cal.setDate(new Date().getTime());

'calendar'フィールドは私のCalendarViewです。輸入:

import android.widget.CalendarView;
import java.util.Date;

エラーなしで現在の日付を取得しました。


0

これは私が使用したコードです:

             Date date = new Date();  // to get the date
             SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); // getting date in this format
             String formattedDate = df.format(date.getTime());
             text.setText(formattedDate);

0

私はすでにこれを使用しました:

Date What_Is_Today=Calendar.getInstance().getTime();
SimpleDateFormat Dateformat = new SimpleDateFormat("dd-MM-yyyy");
String Today=Dateformatf.format(What_Is_Today);

Toast.makeText(this,Today,Toast.LENGTH_LONG).show();

最初に時間を取得し、次にシンプルな日付フォーマットを宣言し(19-6-2018のような日付を取得するため)、フォーマットを使用して日付を文字列に変更します。


0

簡単な日付形式を取得するための1行のコード:

SimpleDateFormat.getDateInstance().format(Date())

出力:2020年5月18日

SimpleDateFormat.getDateTimeInstance().format(Date())

出力:2020年5月18日11:00:39 AM

SimpleDateFormat.getTimeInstance().format(Date())

出力:11 : 00 : 39 AM

この答えがこの日付と時刻の形式を取得するのに十分であることを願っています... :)


時代遅れ長いと悪名高い厄介使用するように若いものを教えないでくださいSimpleDateFormatDateFormatクラスを。少なくとも最初の選択肢としてではない。予約なしではありません。今日、私たちはjava.time、最新のJava日時APIとそのを非常によく利用していますDateTimeFormatter。はい、Androidで使用できます。古いAndroidについては、AndroidプロジェクトでThreeTenABPを使用する方法を参照してください。
Ole VV

-1

これは私が使用したコードです:

final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);

// Set current date into textview
tvDisplayDate.setText(new StringBuilder()
    .append(month + 1).append("-") // Month is 0 based, add 1
    .append(day).append("-")
    .append(year).append("   Today is :" + thursday ) );

// Set current date into datepicker
dpResult.init(year, month, day, null);
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.