Wyświetl aktualną godzinę i datę w aplikacji na Androida


Odpowiedzi:


301

Dobra, nie tak trudne, ponieważ istnieje kilka metod, aby to zrobić. Zakładam, że chcesz umieścić bieżącą datę i godzinę w TextView.

String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date());

// textView is the TextView view that should display it
textView.setText(currentDateTimeString);

Dokumentacja zawiera więcej informacji, które można łatwo znaleźć tutaj . Znajdziesz tam więcej informacji na temat zmiany formatu używanego do konwersji.


43
Proszę - wyraźniej! Jaki jest błąd? Czy zaimportowałeś niewłaściwą klasę DateFormat? To java.text.DateFormati NIE android.text.format.DateFormat! I to jest java.util.Datei NIE java.sql.Date! Mała wskazówka na temat zadawania pytań: staraj się być precyzyjny, np .: zadeklaruj, co masz na myśli, mówiąc „wyświetl” w swoim pytaniu. A kiedy wpiszesz moje wiersze - zarówno Date, jak i DateFormat, oczywiście, muszą zostać zaimportowane - jeśli istnieje wybór 2 dla każdego, przynajmniej możesz spróbować dowolnej kombinacji: to tylko 4!
— Zordid

przepraszam proszę pana, mam datę, a nie czas. podobnie możemy dostać czas?
— BIBEKRBARAL

28
Spójrz na developer.android.com/reference/java/text/SimpleDateFormat.html - tam możesz zobaczyć, jak dokładnie zdefiniować , co chcesz być w ciągu wyjściowym. Np. Na czas "HH:mm:ss"! Całkowicie:currentTimeString = new SimpleDateFormat("HH:mm:ss").format(new Date());
— Zordid

2
Jest też DateFormat.getTimeInstance()i DateFormat.getDateTimeInstance().
— Felix

Jak to jest wydajne? Powiedzmy, że potrzebujesz czasu na nieustanne strzelanie. Czy jest coś bardziej wydajnego niż tworzenie nowego obiektu Date za każdym razem?
— keshav.bahadoor

125
public class XYZ extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);

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

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = df.format(c.getTime());
        // formattedDate have current date/time
        Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();


      // Now we display formattedDate value in TextView
        TextView txtView = new TextView(this);
        txtView.setText("Current Date and Time : "+formattedDate);
        txtView.setGravity(Gravity.CENTER);
        txtView.setTextSize(20);
        setContentView(txtView);
    }

}

wprowadź opis zdjęcia tutaj


1
android.os.Build.VERSION.SDK_INT> = android.os.Build.VERSION_CODES.N (24).
— kangear

Jak zadeklarować, SimpleDateFormatponieważ mam nie można znaleźć klasy symbolu
— dubis

51
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    Thread myThread = null;

    Runnable runnable = new CountDownRunner();
    myThread= new Thread(runnable);   
    myThread.start();

}

public void doWork() {
    runOnUiThread(new Runnable() {
        public void run() {
            try{
                TextView txtCurrentTime= (TextView)findViewById(R.id.lbltime);
                    Date dt = new Date();
                    int hours = dt.getHours();
                    int minutes = dt.getMinutes();
                    int seconds = dt.getSeconds();
                    String curTime = hours + ":" + minutes + ":" + seconds;
                    txtCurrentTime.setText(curTime);
            }catch (Exception e) {}
        }
    });
}


class CountDownRunner implements Runnable{
    // @Override
    public void run() {
            while(!Thread.currentThread().isInterrupted()){
                try {
                doWork();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                }catch(Exception e){
                }
            }
    }
}

@Harshit ta funkcja jest dostarczana z zestawem Android SDK, o ile Twoja klasa rozszerza aktywność
— Carlos P

2
Wiem, że to stare pytanie, ale jeśli ktoś znajdzie go w Google, takim jak ja, powinien wiedzieć, że metody Date.getX są przestarzałe.
— tobi

38

Oczywiste opcje wyświetlania czasu to AnalogClockWidok i DigitalClockWidok .

Na przykład następujący układ:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:orientation="vertical">

    <AnalogClock
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"/>

    <DigitalClock 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:gravity="center" 
        android:textSize="20sp"/>
</LinearLayout>

Wygląda tak:

zrzut ekranu


4
Szanowny Panie, chcę wyświetlić aktualny czas za pomocą setText.
— BIBEKRBARAL

5
Czuję się jak głupie gówno po przeczytaniu tej oczywistej odpowiedzi! Zaimplementowałem własne uruchamianie, uśpienie na określony czas i tak dalej, gdy oczywistą odpowiedzią był XML-one-liner! Ogromne podziękowania (ponad rok po poście) :-)
— dbm

6
W 2015 roku jest przestarzałe i zaleca się stosowanie TextClock. :)
— Evilripper

1
AnalogClock jest przestarzały na poziomie API 23, a AnalogClock i DigitalClock pokazują tylko bieżącą godzinę, ale nie bieżącą datę.
— Zafer

34

Jeśli chcesz mieć pojedynczy wiersz kodu:

String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

Wynik to "2016-09-25 16:50:34"


23

Moje własne działające rozwiązanie:

Calendar c = Calendar.getInstance();

String sDate = c.get(Calendar.YEAR) + "-" 
+ c.get(Calendar.MONTH)
+ "-" + c.get(Calendar.DAY_OF_MONTH) 
+ " at " + c.get(Calendar.HOUR_OF_DAY) 
+ ":" + c.get(Calendar.MINUTE);

Mam nadzieję że to pomoże!


Zastanawiam się, dlaczego c.get (Calendar.MONTH) zwraca 5, gdy jest rzekomo 6? Moje urządzenie ma prawidłowe ustawienia czasu.
— Kris,

O tak, ale dlaczego muszą to robić, skoro inne zmienne były dokładne. :)
— Kris,

1
Kalendarz c = Calendar.getInstance (); int miesiąc = c.get (Calendar.MONTH) + 1; Ciąg sDate = miesiąc + "-" + c.get (Calendar.DAY_OF_MONTH) + "-" + c.get (Calendar.YEAR) + "-" + c.get (Calendar.HOUR_OF_DAY) + ":" + c. pobierz (Calendar.MINUTE); to działa dobrze
— 577732

20

Jeśli chcesz uzyskać datę i godzinę według określonego wzoru, możesz użyć

Date d = new Date();
CharSequence s = DateFormat.format("yyyy-MM-dd hh:mm:ss", d.getTime());

15

Od Jak uzyskać pełną datę i prawidłowy format? :

Proszę użyć

android.text.format.DateFormat.getDateFormat(Context context)
android.text.format.DateFormat.getTimeFormat(Context context)

aby uzyskać prawidłowe formaty czasu i daty w świetle bieżących ustawień użytkownika (na przykład format godziny 12/24).

import android.text.format.DateFormat;

private void some() {
    final Calendar t = Calendar.getInstance();
    textView.setText(DateFormat.getTimeFormat(this/*Context*/).format(t.getTime()));
}

10

Oto kod, który działał dla mnie. Spróbuj tego. Jest to prosta metoda, która wymaga czasu i daty z wywołania systemowego. Metoda Datetime (), gdziekolwiek potrzebujesz.

public static String Datetime()
{
    Calendar c = Calendar .getInstance();
    System.out.println("Current time => "+c.getTime());
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mms");
    formattedDate = df.format(c.getTime());
    return formattedDate;
}

9

Posługiwać się:

Calendar c = Calendar.getInstance();

int seconds = c.get(Calendar.SECOND);
int minutes = c.get(Calendar.MINUTE);
int hour = c.get(Calendar.HOUR);
String time = hour + ":" + minutes + ":" + seconds;


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

// Assuming that you need date and time in a separate
// textview named txt_date and txt_time.

txt_date.setText(date);
txt_time.setText(time);

7
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); 

Użyj formattedDatejako Stringwypełnionej daty.
W moim przypadku:mDateButton.setText(formattedDate);


6
Calendar c = Calendar.getInstance();
int month=c.get(Calendar.MONTH)+1;
String sDate = c.get(Calendar.YEAR) + "-" + month+ "-" + c.get(Calendar.DAY_OF_MONTH) +
"T" + c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);

To da format daty i godziny, jak 2010-05-24T18: 13: 00



6

Aby wyświetlić funkcję bieżącej daty:

Calendar c = Calendar.getInstance();

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String date = df.format(c.getTime());
Date.setText(date);

Musisz zaimportować

import java.text.SimpleDateFormat; import java.util.Calendar;

Musisz użyć

TextView Date;
Date = (TextView) findViewById(R.id.Date);

5

Dałoby to bieżącą datę i godzinę:

public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return dt;
}

5

Po prostu skopiuj ten kod i mam nadzieję, że to zadziała.

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());

3
String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show();

3

Wypróbuj poniższy kod:

SimpleDateFormat dateFormat = new SimpleDateFormat(
                                    "yyyy/MM/dd HH:mm:ss");

Calendar cal = Calendar.getInstance();
System.out.println("time => " + dateFormat.format(cal.getTime()));

String time_str = dateFormat.format(cal.getTime());

String[] s = time_str.split(" ");

for (int i = 0; i < s.length; i++) {
     System.out.println("date  => " + s[i]);
}

int year_sys = Integer.parseInt(s[0].split("/")[0]);
int month_sys = Integer.parseInt(s[0].split("/")[1]);
int day_sys = Integer.parseInt(s[0].split("/")[2]);

int hour_sys = Integer.parseInt(s[1].split(":")[0]);
int min_sys = Integer.parseInt(s[1].split(":")[1]);

System.out.println("year_sys  => " + year_sys);
System.out.println("month_sys  => " + month_sys);
System.out.println("day_sys  => " + day_sys);

System.out.println("hour_sys  => " + hour_sys);
System.out.println("min_sys  => " + min_sys);

3

Możesz spróbować w ten sposób

Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String strDate = "Current Time : " + mdformat.format(calendar.getTime());

2

Jeśli chcesz pracować z datą / godziną w Androidzie, polecam użyć ThreeTenABP, który jest wersją java.time.*pakietu (dostępną od API 26 na Androida) dostarczaną z Javą 8 dostępną jako zamiennik dla java.util.Datei java.util.Calendar.

LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
String date = localDate.format(formatter);
textView.setText(date);

1
Mówiąc wprost, jestem pewien, że miałeś na myśli właściwą rzecz: java.time jest wbudowany z poziomu interfejsu API Androida 26. ThreeTenABP jest tym, czego używasz, aby uzyskać praktycznie taką samą funkcjonalność na niższych poziomach API . Kod może więc działać zarówno na niskim, jak i na wysokim poziomie.
— Ole VV,

2
A ponieważ pytanie dotyczyło wyświetlania daty i godziny , w tym celu można użyć na przykład ZonedDateTimezamiast LocalDatei DateTimeFormatter.ofLocalizedDateTimezamiast ofLocalizedDate. W przeciwnym razie kod będzie taki sam.
— Ole VV,

1

Aby wyświetlić bieżącą datę i godzinę w widoku tekstu

    /// For Show Date
    String currentDateString = DateFormat.getDateInstance().format(new Date());
    // textView is the TextView view that should display it
    textViewdate.setText(currentDateString);
    /// For Show Time
    String currentTimeString = DateFormat.getTimeInstance().format(new Date());
    // textView is the TextView view that should display it
    textViewtime.setText(currentTimeString);

Sprawdź pełny kod Androida - Wyświetl bieżącą datę i godzinę w przykładzie Android Studio z kodem źródłowym


0

Aby uzyskać bieżącą datę / godzinę, użyj następującego fragmentu kodu:

Aby użyć czasu :

SimpleDateFormat simpleDateFormatTime = new SimpleDateFormat("HH:mm", Locale.getDefault());
String strTime = simpleDateFormatTime.format(now.getTime());

Aby użyć daty :

SimpleDateFormat simpleDateFormatDate = new SimpleDateFormat("E, MMM dd, yyyy", Locale.getDefault());    
String strDate = simpleDateFormatDate.format(now.getTime());

i jesteś gotowy iść.


0
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
Date date = Calendar.getInstance().getTime();
String sDate = format.format(date);//31-12-9999
int mYear = c.get(Calendar.YEAR);//9999
int mMonth = c.get(Calendar.MONTH);
mMonth = mMonth + 1;//12
int hrs = c.get(Calendar.HOUR_OF_DAY);//24
int min = c.get(Calendar.MINUTE);//59
String AMPM;
if (c.get(Calendar.AM_PM) == 0) {
    AMPM = "AM";
} else {
    AMPM = "PM";
}
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.