Jak uzyskać aktualny czas i datę w Androidzie

Jak mogę uzyskać aktualną godzinę i datę w aplikacji na Androida?

Author: Peter Mortensen, 2011-03-20

30 answers

Możesz użyć:

import java.util.Calendar

Date currentTime = Calendar.getInstance().getTime();

Istnieje wiele stałych w kalendarzu dla wszystkiego, czego potrzebujesz.

Edit:
Sprawdź dokumentacja klasy kalendarza

 1367
Author: miken32,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-26 07:28:08

Możesz (ale nie powinieneś już - patrz poniżej!) użyj android.tekst.format.CZAS :

Time now = new Time();
now.setToNow();

Z odnośnika powyżej:

Klasa czasu jest szybszą wymianą dla Javy.util.Kalendarz i java.util.GregorianCalendar classes. Przykład klasy czasu reprezentuje moment w czasie, określony z drugą precyzją.


Uwaga 1: Minęło kilka lat odkąd napisałem tę odpowiedź, i chodzi o stara, specyficzna dla Androida, a teraz przestarzała Klasa. Google now mówi że "[t]jego klasa ma wiele problemów i zaleca się, aby GregorianCalendar został użyty zamiast tego".


Uwaga 2: mimo że klasa Time ma metodę toMillis(ignoreDaylightSavings), jest to tylko wygoda do przekazania metodom, które oczekują czasu w milisekundach. Wartość czasu wynosi tylko z dokładnością do jednej sekundy ; część milisekund zawsze wynosi 000. Jeśli w pętli do

Time time = new Time();   time.setToNow();
Log.d("TIME TEST", Long.toString(time.toMillis(false)));
... do something that takes more than one millisecond, but less than one second ...

Otrzymana sekwencja będzie powtarzać tę samą wartość, np. 1410543204000, aż do rozpoczęcia następnej sekundy, w którym to czasie 1410543205000 zacznie się powtarzać.

 489
Author: Thomas Padron-McCarthy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-15 08:04:17

Jeśli chcesz uzyskać datę i godzinę w określonym wzorze, możesz użyć następującego wzoru:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
String currentDateandTime = sdf.format(new Date());

Lub

Data :

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

Czas:

String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
 394
Author: Miciurash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-26 19:33:27

Dla tych, którzy wolą niestandardowy format, możesz użyć:

DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());

Natomiast można mieć wzorce Dateformatowe takie jak:

"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01
 237
Author: ANemati,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-10 03:29:26

W rzeczywistości bezpieczniej jest ustawić bieżącą strefę czasową na urządzeniu za pomocą Time.getCurrentTimezone(), w przeciwnym razie otrzymasz bieżący czas w UTC.

Time today = new Time(Time.getCurrentTimezone());
today.setToNow();

Następnie możesz uzyskać wszystkie pola daty, na przykład:

textViewDay.setText(today.monthDay + "");             // Day of the month (1-31)
textViewMonth.setText(today.month + "");              // Month (0-11)
textViewYear.setText(today.year + "");                // Year 
textViewTime.setText(today.format("%k:%M:%S"));  // Current time

Zobacz android.tekst.format.Czas klasa dla wszystkich szczegółów.

UPDATE

Jak Wiele osób wskazuje, Google twierdzi, że ta klasa ma wiele problemów i nie powinna być już używana:

Ta klasa ma liczba problemów i zaleca się, aby Zamiast tego używa się GregorianCalendar.

Znane problemy:

Ze względów historycznych podczas wykonywania obliczeń czasu wszystkie obecnie arytmetyka odbywa się przy użyciu 32-bitowych liczb całkowitych. Ogranicza to niezawodny zakres czasu reprezentowany od 1902 do 2037 roku.Zobacz też artykuł Wikipedii na temat problemu roku 2038 o szczegóły. Nie polegaj na to zachowanie; może się zmienić w przyszłości. Calling switchTimezone (String) Na dacie, która nie może istnieje, np. ściana czas, który został pominięty z powodu przejścia DST, spowoduje datę w 1969 roku (tj. -1, czyli 1 sekunda przed 1 stycznia 1970 UTC). Wiele z formatowanie / parsowanie przyjmuje tekst ASCII i dlatego nie jest odpowiednie do użytku ze skryptami spoza ASCII.

 128
Author: kaneda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-26 14:47:56

Dla bieżącej daty i godziny, użyj:

String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());

Które Wyjście:

Feb 27, 2012 5:41:23 PM
 82
Author: Kirit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-10 03:27:22

Tl; dr

Instant.now()  // Current moment in UTC.

...lub...

ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )  // In a particular time zone

Szczegóły

Pozostałe odpowiedzi, choć poprawne, są nieaktualne. Stare klasy date-time okazały się źle zaprojektowane, mylące i kłopotliwe.

Java.czas

Te stare klasy zostały wyparte przez Javę.czas ramy.

Te nowe klasy są inspirowane bardzo udanym projektem Joda-Time , zdefiniowanym przez JSR 310 i rozszerzonym przez threeten-Extra .

Zobacz Oracle Tutorial .

Instant

An Instant jest momentem na osi czasu w UTC z rozdzielczością do nanosekund.

 Instant instant = Instant.now(); // Current moment in UTC.

Czas Strefa

Zastosuj strefę czasową (ZoneId) aby uzyskać ZonedDateTime. Jeśli pominiesz strefę czasową, domyślna Strefa czasowa JVM zostanie domyślnie zastosowana. Lepiej wyraźnie określić pożądaną / oczekiwaną strefę czasową.

Użyj odpowiednich nazw stref czasowych w formacie continent/region, takich jak America/Montreal, Europe/Brussels, lub Asia/Kolkata. Nigdy nie używaj skrótów 3-4 literowych, takich jak EST lub IST, ponieważ nie są one ani znormalizowane, ani wyjątkowe.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Tabela typów daty i czasu w Javie, zarówno nowoczesnych, jak i starszych

Generowanie Strun

Możesz łatwo wygenerować String jako tekstową reprezentację wartości data-czas. Możesz wybrać format standardowy, własny format niestandardowy lub automatycznie zlokalizowany.

ISO 8601

Możesz wywołać metody toString, aby uzyskać formatowanie tekstu przy użyciu wspólnego i sensownego standardu ISO 8601.

String output = instant.toString();

2016-03-23T03: 09: 01.613 Z

Zauważ, że dla ZonedDateTime, metoda toString rozszerza standard ISO 8601 przez dodanie nazwy strefy czasowej w nawiasach kwadratowych. Niezwykle przydatne i ważne informacje, ale nie standardowe.

[[31]} 2016-03-22t20:09:01.613-08:00 [America/Los_Angeles]

Własny format

Lub określ swój własny wzór formatowania za pomocą DateTimeFormatter klasy.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );

Określ a Locale dla ludzkiego języka (Angielski, Francuski itd.) używać w tłumaczeniu nazwy dnia / miesiąca, a także w definiowaniu norm kulturowych, takich jak kolejność roku, miesiąca i daty. Zauważ, że Locale nie ma nic wspólnego ze strefą czasową.

formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );

Lokalizowanie

[[31]}Jeszcze lepiej, niech java.czas wykonaj pracę lokalizowania automatycznie.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) );  // Or Locale.CANADA_FRENCH and so on.

O java.czas

The java.czas framework jest wbudowany w Javę 8 i Później. Klasy te zastępują kłopotliwe stare dziedzictwo klasy date-time, takie jak java.util.Date, Calendar, & SimpleDateFormat.

The Joda-czas projekt, obecnie w trybie konserwacji , radzi migrację do java.czas klasy.

Aby dowiedzieć się więcej, Zobacz samouczek Oracle. I wyszukaj przepełnienie stosu dla wielu przykładów i wyjaśnień. Specyfikacja jest JSR 310.

Możesz wymienić Javę.obiekty time bezpośrednio z bazą danych. Użyj sterownika JDBCzgodnego z JDBC 4.2 lub nowszego. Nie ma potrzeby stosowania łańcuchów, nie ma potrzeby stosowania klas java.sql.*.

Skąd pobrać Javę.zajęcia czasowe?

Tabela z listą implementacji * java.czas * technologia do wykorzystania na które wersje Java i Android.

 67
Author: Basil Bourque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-28 15:15:00

Spróbuj w ten sposób wszystkie formaty są podane poniżej, aby uzyskać format daty i godziny.

    Calendar c = Calendar.getInstance();
    SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss aa");
    String datetime = dateformat.format(c.getTime());
    System.out.println(datetime);

pierwszy

drugi trzeci

 62
Author: Amitsharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-06 08:45:59

Do bieżącego czasu można użyć System.currentTimeMillis(), który jest standardem w Javie. Następnie możesz go użyć do utworzenia daty

Date currentDate = new Date(System.currentTimeMillis());

I jak wspomniano przez innych, aby utworzyć czas

Time currentTime = new Time();
currentTime.setToNow();
 54
Author: JosephL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-25 23:07:29

Możesz użyć kodu:

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

Wyjście:

2014-11-11 00:47:55

Możesz również uzyskać więcej opcji formatowania dla SimpleDateFormat z tutaj .

 38
Author: Himanshu Aggarwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-10 19:17:21

Łatwo, możesz podzielić czas, aby uzyskać oddzielne wartości dla bieżącego czasu, w następujący sposób:

Calendar cal = Calendar.getInstance(); 

  int millisecond = cal.get(Calendar.MILLISECOND);
  int second = cal.get(Calendar.SECOND);
  int minute = cal.get(Calendar.MINUTE);
        //12 hour format
  int hour = cal.get(Calendar.HOUR);
        //24 hour format
  int hourofday = cal.get(Calendar.HOUR_OF_DAY);

To samo dotyczy daty, jak następuje:

Calendar cal = Calendar.getInstance(); 

  int dayofyear = cal.get(Calendar.DAY_OF_YEAR);
  int year = cal.get(Calendar.YEAR);
  int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
  int dayofmonth = cal.get(Calendar.DAY_OF_MONTH);
 33
Author: SkateJerrySkate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-13 18:17:13

Istnieje kilka opcji, ponieważ Android to głównie Java, ale jeśli chcesz go napisać w widoku tekstowym, następujący kod zrobiłby sztuczkę:

String currentDateTimeString = DateFormat.getDateInstance().format(new Date());

// textView is the TextView view that should display it
textView.setText(currentDateTimeString);
 28
Author: dLobatog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-09 15:40:46
SimpleDateFormat databaseDateTimeFormate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat databaseDateFormate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf1 = new SimpleDateFormat("dd.MM.yy");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, MMM d, ''yy");
SimpleDateFormat sdf4 = new SimpleDateFormat("h:mm a");
SimpleDateFormat sdf5 = new SimpleDateFormat("h:mm");
SimpleDateFormat sdf6 = new SimpleDateFormat("H:mm:ss:SSS");
SimpleDateFormat sdf7 = new SimpleDateFormat("K:mm a,z");
SimpleDateFormat sdf8 = new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm aaa");


String currentDateandTime = databaseDateTimeFormate.format(new Date());     //2009-06-30 08:29:36
String currentDateandTime = databaseDateFormate.format(new Date());     //2009-06-30
String currentDateandTime = sdf1.format(new Date());     //30.06.09
String currentDateandTime = sdf2.format(new Date());     //2009.06.30 AD at 08:29:36 PDT
String currentDateandTime = sdf3.format(new Date());     //Tue, Jun 30, '09
String currentDateandTime = sdf4.format(new Date());     //8:29 PM
String currentDateandTime = sdf5.format(new Date());     //8:29
String currentDateandTime = sdf6.format(new Date());     //8:28:36:249
String currentDateandTime = sdf7.format(new Date());     //8:29 AM,PDT
String currentDateandTime = sdf8.format(new Date());     //2009.June.30 AD 08:29 AM

Wzorce formatu daty

G   Era designator (before christ, after christ)
y   Year (e.g. 12 or 2012). Use either yy or yyyy.
M   Month in year. Number of M's determine length of format (e.g. MM, MMM or MMMMM)
d   Day in month. Number of d's determine length of format (e.g. d or dd)
h   Hour of day, 1-12 (AM / PM) (normally hh)
H   Hour of day, 0-23 (normally HH)
m   Minute in hour, 0-59 (normally mm)
s   Second in minute, 0-59 (normally ss)
S   Millisecond in second, 0-999 (normally SSS)
E   Day in week (e.g Monday, Tuesday etc.)
D   Day in year (1-366)
F   Day of week in month (e.g. 1st Thursday of December)
w   Week in year (1-53)
W   Week in month (0-5)
a   AM / PM marker
k   Hour in day (1-24, unlike HH's 0-23)
K   Hour in day, AM / PM (0-11)
z   Time Zone
 24
Author: Vignesh KM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-04 11:40:23
final Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR);
    int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH);

textView.setText(""+mDay+"-"+mMonth+"-"+mYear);
 17
Author: Alex Muriithi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-20 21:17:36

Jest to metoda, która będzie przydatna do uzyskania daty i godziny:

private String getDate(){
    DateFormat dfDate = new SimpleDateFormat("yyyy/MM/dd");
    String date=dfDate.format(Calendar.getInstance().getTime());
    DateFormat dfTime = new SimpleDateFormat("HH:mm");
    String time = dfTime.format(Calendar.getInstance().getTime());
    return date + " " + time;
}

Możesz wywołać tę metodę i uzyskać bieżące wartości daty i czasu:

2017/01//09 19:23
 15
Author: Jorgesys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-09 19:41:02

Dla bieżącej daty i godziny z formatem Użyj

W Javie

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());
Log.d("Date","DATE : " + strDate)

W Kotlinie

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val current = LocalDateTime.now()
    val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss")
    var myDate: String =  current.format(formatter)
    Log.d("Date","DATE : " + myDate)
} else {
    var date = Date()
    val formatter = SimpleDateFormat("MMM dd yyyy HH:mma")
    val myDate: String = formatter.format(date)
    Log.d("Date","DATE : " + myDate)
}

wzorce formatowania dat

"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01
 15
Author: Vipul Prajapati,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-07-30 15:56:10

Jeśli potrzebujesz aktualnej daty:

Calendar cc = Calendar.getInstance();
int year = cc.get(Calendar.YEAR);
int month = cc.get(Calendar.MONTH);
int mDay = cc.get(Calendar.DAY_OF_MONTH);
System.out.println("Date", year + ":" + month + ":" + mDay);

Jeśli potrzebujesz aktualnego czasu:

 int mHour = cc.get(Calendar.HOUR_OF_DAY);
 int mMinute = cc.get(Calendar.MINUTE);
 System.out.println("time_format" + String.format("%02d:%02d", mHour , mMinute));
 13
Author: RejoylinLokeshwaran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-25 09:48:35
Time time = new Time();
time.setToNow();
System.out.println("time: " + time.hour+":"+time.minute);

To da ci, na przykład, 12: 32.

Pamiętaj, aby zaimportować Androida.tekst.format.Czas;

 12
Author: Sam Haque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-18 12:31:21
    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);
 12
Author: duggu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-10 03:28:50

Możesz również używać Androida.os.SystemClock. Na przykład SystemClock.funkcja elapsedRealtime () zapewnia dokładniejsze odczyty czasu, gdy telefon jest w stanie uśpienia.

 11
Author: Quadroid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-09 12:13:02

Możesz po prostu użyć następującego kodu:

 DateFormat df = new SimpleDateFormat("HH:mm"); // Format time
 String time = df.format(Calendar.getInstance().getTime());

 DateFormat df1 = new SimpleDateFormat("yyyy/MM/dd"); // Format date
 String date = df1.format(Calendar.getInstance().getTime());
 10
Author: Ali Ziaee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-17 22:47:43

Dla niestandardowego formatu czasu i Daty:

    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ",Locale.ENGLISH);
    String cDateTime=dateFormat.format(new Date());

Wyjście jest jak poniżej w formacie: 2015-06-18T10: 15: 56-05: 00

 9
Author: Omar Faroque Anik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-18 15:20:28
Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();
 8
Author: Muhammad Aamir Ali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-16 09:02:26
Time now = new Time();
now.setToNow();
Spróbuj to działa również dla mnie.
 8
Author: TheMan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-30 07:42:39

Możesz uzyskać datę używając:

Time t = new Time(Time.getCurrentTimezone());
t.setToNow();
String date = t.format("%Y/%m/%d");

To daje wynik w ładnej formie, jak w tym przykładzie: "2014/02/09".

 8
Author: Annabelle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-10 03:30:10

Cóż miałem problemy z niektórymi odpowiedziami przez API więc wrzuciłem ten kod, mam nadzieję, że im służy:

Time t = new Time(Time.getCurrentTimezone());
t.setToNow();
String date1 = t.format("%Y/%m/%d");

Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa", Locale.ENGLISH);
String var = dateFormat.format(date);
String horafecha = var+ " - " + date1;

tvTime.setText(horafecha);

Wyjście: 03: 25 PM-2017/10/03

 7
Author: Charlie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-02 16:45:24

Spróbuj Tego

String mytime = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());
 6
Author: Abhinaw Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-23 14:02:50

Poniżej metoda zwróci bieżącą datę i czas w łańcuchu, użyj innej strefy czasowej zgodnie z rzeczywistą strefą czasową.Użyłem GMT

public static String GetToday(){
    Date presentTime_Date = Calendar.getInstance().getTime();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    return dateFormat.format(presentTime_Date);
}
 5
Author: Danger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-25 11:48:44

Powinieneś używać klasy Calender zgodnie z nowym API. Klasa Date jest przestarzała.

Calendar cal = Calendar.getInstance();

String date = ""+cal.get(Calendar.DATE)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.YEAR);

String time = ""+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE);
 4
Author: Akshay Paliwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-04 07:28:02

Spróbuj użyć poniższego kodu:

 Date date = new Date();
 SimpleDateFormat dateFormatWithZone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.getDefault());  
 String currentDate = dateFormatWithZone.format(date);
 4
Author: Manikandan K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-17 22:44:47