Jak Mogę uzyskać bieżącą datę i godzinę w UTC lub GMT w Javie?

chcesz poprawić ten post? Podaj szczegółowe odpowiedzi na to pytanie, w tym cytaty i wyjaśnienie, dlaczego Twoja odpowiedź jest prawidłowa. Odpowiedzi bez wystarczającej ilości szczegółów mogą być edytowane lub usuwane.

Kiedy tworzę nowy Date obiekt, jest zainicjalizowany na bieżący czas, ale w lokalnej strefie czasowej. Jak Mogę uzyskać aktualną datę i godzinę w GMT?

Author: Michael Mrozek, 2008-11-21

30 answers

java.util.Date nie ma określonej strefy czasowej, chociaż jej wartość jest najczęściej rozważana w stosunku do UTC. Dlaczego myślisz, że to czas lokalny?

Aby być precyzyjnym: wartość w java.util.Date jest liczbą milisekund od epoki Uniksa, która miała miejsce o północy 1 stycznia 1970, UTC. Ta sama Epoka może być również opisana w innych strefach czasowych, ale tradycyjny opis jest w kategoriach UTC. Ponieważ jest to liczba milisekund od ustalonej epoki, wartość java.util.Date wynosi to samo na całym świecie w każdej konkretnej chwili, niezależnie od lokalnej strefy czasowej.

Podejrzewam, że problem polega na tym, że wyświetlasz go za pomocą instancji Calendar, która używa lokalnej strefy czasowej, lub ewentualnie używając Date.toString(), która również używa lokalnej strefy czasowej, lub instancji SimpleDateFormat, która domyślnie używa również lokalnej strefy czasowej.

Jeśli to nie jest problem, wyślij przykładowy kod.

Polecam jednak użycie Joda-Time w każdym razie, który oferuje wiele jaśniejsze API.

 425
Author: Jon Skeet,
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-01-02 20:00:21

Tl;dr

Instant.now()   // Capture the current moment in UTC. 

Wygeneruj Łańcuch znaków reprezentujący tę wartość:

Instant.now().toString()  

2016-09-13T23: 30: 52.123 Z

Szczegóły

Jako prawidłowa odpowiedź Jon Skeet stwierdził, java.util.Obiekt Date nie posiada strefy czasowej. Ale jego toString implementacja stosuje domyślną strefę czasową JVM podczas generowania reprezentacji łańcuchowej tej wartości date-time. Mylnie dla naiwnego programisty, Data wydaje się mieć strefę czasową, ale nie ma.

The java.util.Date, j.u.Calendar, i java.text.SimpleDateFormat klasy w pakiecie z Javą są notorycznie kłopotliwe. Unikaj ich. zamiast tego użyj jednej z tych właściwych bibliotek daty i czasu:

Java.time (Java 8)

Java 8 przynosi doskonałą nową java.czas.* pakiet do zastąpienia starego java.util.Data / kalendarz zajęć.

[[34]} uzyskanie aktualnego czasu w UTC/GMT jest prostym jednoliniowym ...
Instant instant = Instant.now();

Że Instant klasa jest podstawowym budulcem w Javie.czas, reprezentujący moment na osi czasu w UTC z rozdzielczością nanosekund .

W Javie 8 bieżący moment jest rejestrowany z rozdzielczością do milisekund. Java 9 przynosi świeżą implementację Z Clock rejestruje bieżący moment w górę do pełnej zdolności nanosekund tej klasy, w zależności od możliwości sprzętu zegara komputera hosta.

To metoda toString generuje reprezentację łańcuchową swojej wartości za pomocą jednego określonego formatu ISO 8601 . Format ten wyprowadza zero, trzy, sześć lub dziewięć cyfr cyfry ( milisekundy, mikrosekundy , lub nanosekundy ) jako niezbędne do reprezentowania ułamka sekundy.

Jeśli chcesz bardziej elastyczne formatowanie, lub inne dodatkowe funkcje, a następnie zastosować przesunięcie od-UTC zera, dla samego UTC (ZoneOffset.UTC stała ), aby uzyskać OffsetDateTime.

OffsetDateTime now = OffsetDateTime.now( ZoneOffset.UTC );

Zrzut do konsoli ...

System.out.println( "now.toString(): " + now );

Kiedy biegniesz ...

now.toString(): 2014-01-21T23:42:03.522Z

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


O Javie.czas

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

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

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

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

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

Tabela w tym java.biblioteka czasu do wykorzystania z jaką wersją Javy lub Androida

The ThreeTen-Extra projekt rozszerza Javę.czas z dodatkowymi zajęciami. Ten projekt jest poligonem dla potencjalnych przyszłych dodatków do Javy.czas. Możesz znaleźć tutaj kilka przydatnych klas, takich jak Interval, YearWeek, YearQuarter, oraz więcej .


Joda-Czas

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

Używając Joda-Time trzeciej, darmowej biblioteki open-source, możesz pobrać aktualną datę i czas w jednej linijce kodu.

Joda-czas zainspirował nową Javę.czas.* klasy w Javie 8, ale ma inną architekturę. Możesz używać Joda-Time w starszych wersjach Java. Joda-Time kontynuuje pracę w Javie 8 i jest nadal aktywnie utrzymywana (stan na 2014 rok). Jednak zespół Joda-Time radzi migrację do Javy.czas.

System.out.println( "UTC/GMT date-time in ISO 8601 format: " + new org.joda.time.DateTime( org.joda.time.DateTimeZone.UTC ) );

Bardziej szczegółowy przykładowy kod (Joda-czas 2.3) ...

org.joda.time.DateTime now = new org.joda.time.DateTime(); // Default time zone.
org.joda.time.DateTime zulu = now.toDateTime( org.joda.time.DateTimeZone.UTC );

Zrzut do konsoli ...

System.out.println( "Local time in ISO 8601 format: " + now );
System.out.println( "Same moment in UTC (Zulu): " + zulu );

Kiedy biegniesz ...

Local time in ISO 8601 format: 2014-01-21T15:34:29.933-08:00
Same moment in UTC (Zulu): 2014-01-21T23:34:29.933Z

Aby uzyskać więcej przykładowego kodu wykonującego pracę w strefie czasowej, zobacz moja odpowiedź na podobne pytanie.

Strefa Czasowa

Polecam zawsze określać strefę czasową, a nie poleganie pośrednio na bieżącej domyślnej strefie czasowej JVM (która może się zmienić w dowolnym momencie!). Takie poleganie wydaje się być częstą przyczyną nieporozumień i błędów w pracy z datą.

Podczas wywoływania now() podaj żądaną / oczekiwaną strefę czasową do przypisania. Użyj DateTimeZone klasy.

DateTimeZone zoneMontréal = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zoneMontréal );

Ta klasa posiada stałą dla strefy czasowej UTC .

DateTime now = DateTime.now( DateTimeZone.UTC );

Jeśli naprawdę chcesz użyć bieżącej domyślnej strefy czasowej JVM, wykonaj wyraźne wywołanie, aby Twój kod był samokontrola.

DateTimeZone zoneDefault = DateTimeZone.getDefault();

ISO 8601

Przeczytaj o ISO 8601 formatach. Zarówno java.time I Joda-Time używają sensownych formatów tego standardu jako domyślnych zarówno do parsowania, jak i generowania łańcuchów.


właściwie java.util.Date czy mA strefę czasową, zakopaną głęboko pod warstwami kodu źródłowego. Dla najbardziej praktycznych celów, ta strefa czasowa jest ignorowana. Więc, jako skrót, mówimy java.util.Data nie ma strefy czasowej. Ponadto, że zakopana Strefa czasowa to nie używana przez metodę Date toString; ta metoda używa bieżącej domyślnej strefy czasowej JVM. Tym bardziej należy unikać tej mylącej klasy i trzymać się Joda-Time I Javy.czas.

 377
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-06 14:58:34
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));

//Local time zone   
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

//Time in GMT
return dateFormatLocal.parse( dateFormatGmt.format(new Date()) );
 275
Author: Dan,
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
2010-03-27 07:08:23

To zdecydowanie zwraca czas UTC: jako obiekty typu String i date !

static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

public static Date getUTCdatetimeAsDate() {
    // note: doesn't check for null
    return stringDateToDate(getUTCdatetimeAsString());
}

public static String getUTCdatetimeAsString() {
    final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    final String utcTime = sdf.format(new Date());

    return utcTime;
}

public static Date stringDateToDate(String StrDate) {
    Date dateToReturn = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);

    try {
        dateToReturn = (Date)dateFormat.parse(StrDate);
    }
    catch (ParseException e) {
        e.printStackTrace();
    }

    return dateToReturn;
}
 86
Author: Someone Somewhere,
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-02-19 11:10:25
    Calendar c = Calendar.getInstance();
    System.out.println("current: "+c.getTime());

    TimeZone z = c.getTimeZone();
    int offset = z.getRawOffset();
    if(z.inDaylightTime(new Date())){
        offset = offset + z.getDSTSavings();
    }
    int offsetHrs = offset / 1000 / 60 / 60;
    int offsetMins = offset / 1000 / 60 % 60;

    System.out.println("offset: " + offsetHrs);
    System.out.println("offset: " + offsetMins);

    c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
    c.add(Calendar.MINUTE, (-offsetMins));

    System.out.println("GMT Time: "+c.getTime());
 66
Author: Ahmad Nadeem,
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-05-10 05:20:14

Właściwie to nie czas, ale jego reprezentację można zmienić.

SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(f.format(new Date()));
Czas jest taki sam w każdym punkcie Ziemi, ale nasze postrzeganie czasu może być różne w zależności od lokalizacji.
 56
Author: Antonio,
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-04-25 06:33:08

Kalendarz aGMTCalendar = Kalendarz.getInstance (TimeZone.getTimeZone ("GMT")); Wtedy wszystkie operacje wykonywane przy użyciu obiektu aGMTCalendar będą wykonywane ze strefą czasową GMT i nie będą miały zastosowanego czasu letniego ani stałych korekt

Źle!
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
aGMTCalendar.getTime(); //or getTimeInMillis()

I

Calendar aNotGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT-2"));aNotGMTCalendar.getTime();

Zwróci ten sam czas. Idem dla

new Date(); //it's not GMT.
 18
Author: simpatico,
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-02-10 09:19:52

To działa dla uzyskania milisekund UTC w Androidzie.

Calendar c = Calendar.getInstance();
int utcOffset = c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET);  
Long utcMilliseconds = c.getTimeInMillis() + utcOffset;
 17
Author: moberme,
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-05-16 19:35:11

Ten kod wyświetla bieżący czas UTC.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;


public class Test
{
    public static void main(final String[] args) throws ParseException
    {
        final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        f.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println(f.format(new Date()));
    }
}

Wynik

2013-10-26 14:37:48 UTC
 17
Author: Adam,
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-10-26 14:39:47

Oto, co wydaje się być nieprawidłowe W odpowiedź Jona Skeeta. Powiedział:

java.util.Date jest zawsze w UTC. Co sprawia, że myślisz, że to w lokalnym czas? Podejrzewam, że problem polega na tym, że wyświetlasz go poprzez przykład kalendarza, który używa lokalnej strefy czasowej, lub ewentualnie za pomocą {[3] } który również używa lokalnej strefy czasowej.

Kod:

System.out.println(new java.util.Date().getHours() + " hours");

Podaje godziny lokalne, nie GMT (UTC hours), używając no Calendar i no SimpleDateFormat w wszystkie.

Dlatego wydaje się, że coś jest nie tak.

Zestawienie odpowiedzi, kod:

System.out.println(Calendar.getInstance(TimeZone.getTimeZone("GMT"))
                           .get(Calendar.HOUR_OF_DAY) + " Hours");

Pokazuje godziny GMT zamiast lokalnych godzin -- zauważ, że getTime.getHours() nie ma, ponieważ utworzyłoby to obiekt Date(), który teoretycznie przechowuje datę w GMT, ale zwraca godziny w lokalnej strefie czasowej.

 10
Author: Dana Wilson,
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-03-04 08:48:16

Możesz użyć:

Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));

Wtedy wszystkie operacje wykonywane przy użyciu obiektu aGMTCalendar będą wykonywane ze strefą czasową GMT i nie będą miały zastosowania czas letni lub stałe przesunięcia. Myślę, że poprzedni plakat jest poprawny, że obiekt Date() zawsze zwraca GMT dopiero wtedy, gdy zrobisz coś z obiektem date, zostanie on przekonwertowany do lokalnej strefy czasowej.

 7
Author: mjh2007,
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
2010-01-26 16:32:00

Jeśli chcesz obiekt daty z polami dostosowanymi do UTC, możesz to zrobić tak z Joda Time :

import org.joda.time.DateTimeZone;
import java.util.Date;

...

Date local = new Date();
System.out.println("Local: " + local);
DateTimeZone zone = DateTimeZone.getDefault();
long utc = zone.convertLocalToUTC(local.getTime(), false);
System.out.println("UTC: " + new Date(utc));
 7
Author: huljas,
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-05-04 10:51:55
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(date));
 6
Author: Justin,
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-01-20 11:52:47

Oto moja implementacja toUTC:

    public static Date toUTC(Date date){
    long datems = date.getTime();
    long timezoneoffset = TimeZone.getDefault().getOffset(datems);
    datems -= timezoneoffset;
    return new Date(datems);
}

Jest prawdopodobnie kilka sposobów, aby to poprawić, ale to działa dla mnie.

 6
Author: Ashallar,
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-08-31 15:10:16

Możesz bezpośrednio użyć tego

SimpleDateFormat dateFormatGmt = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(new Date())+"");
 6
Author: nithinreddy,
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-01-17 05:35:37

Z:

Calendar cal = Calendar.getInstance();

Następnie cal mają aktualną datę i godzinę.
Możesz również uzyskać bieżącą datę i godzinę dla strefy czasowej za pomocą:

Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT-2"));

Możesz zapytać cal.get(Calendar.DATE); lub inną stałą kalendarza o inne szczegóły.
Data i znacznik czasu są przestarzałe w języku Java. Klasa Kalendarza to nie jest.

 5
Author: user2427,
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
2008-11-21 13:10:06

Tutaj inna sugestia, aby uzyskać obiekt znacznika czasu GMT:

import java.sql.Timestamp;
import java.util.Calendar;

...

private static Timestamp getGMT() {
   Calendar cal = Calendar.getInstance();
   return new Timestamp(cal.getTimeInMillis()
                       -cal.get(Calendar.ZONE_OFFSET)
                       -cal.get(Calendar.DST_OFFSET));
}
 5
Author: Rene,
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-05-09 10:34:25

Oto inny sposób na uzyskanie czasu GMT w formacie String

String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z" ;
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateTimeString =  sdf.format(new Date());
 5
Author: shahtapa,
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-01 04:29:56

Przykładowy kod do renderowania czasu systemowego w określonej strefie czasowej i określonym formacie.

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

public class TimZoneTest {
    public static void main (String[] args){
        //<GMT><+/-><hour>:<minutes>
        // Any screw up in this format, timezone defaults to GMT QUIETLY. So test your format a few times.

        System.out.println(my_time_in("GMT-5:00", "MM/dd/yyyy HH:mm:ss") );
        System.out.println(my_time_in("GMT+5:30", "'at' HH:mm a z 'on' MM/dd/yyyy"));

        System.out.println("---------------------------------------------");
        // Alternate format 
        System.out.println(my_time_in("America/Los_Angeles", "'at' HH:mm a z 'on' MM/dd/yyyy") );
        System.out.println(my_time_in("America/Buenos_Aires", "'at' HH:mm a z 'on' MM/dd/yyyy") );


    }

    public static String my_time_in(String target_time_zone, String format){
        TimeZone tz = TimeZone.getTimeZone(target_time_zone);
        Date date = Calendar.getInstance().getTime();
        SimpleDateFormat date_format_gmt = new SimpleDateFormat(format);
        date_format_gmt.setTimeZone(tz);
        return date_format_gmt.format(date);
    }

}

Wyjście

10/08/2011 21:07:21
at 07:37 AM GMT+05:30 on 10/09/2011
at 19:07 PM PDT on 10/08/2011
at 23:07 PM ART on 10/08/2011
 3
Author: so_mv,
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-09 02:12:40

Aby to uprościć, aby utworzyć Date w UTC możesz użyć Calendar :

Calendar.getInstance(TimeZone.getTimeZone("UTC"));

, który zbuduje nową instancję dla Calendar używając " UTC " TimeZone.

Jeśli potrzebujesz Date obiektu z tego kalendarza, możesz po prostu użyć getTime().

 3
Author: Ovidiu Latcu,
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-05-17 13:04:37

Konwersja bieżącej daty w UTC:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

DateTimeZone dateTimeZone = DateTimeZone.getDefault(); //Default Time Zone

DateTime currDateTime = new DateTime(); //Current DateTime

long utcTime = dateTimeZone.convertLocalToUTC(currDateTime .getMillis(), false);

String currTime = formatter.print(utcTime); //UTC time converted to string from long in format of formatter

currDateTime = formatter.parseDateTime(currTime); //Converted to DateTime in UTC
 3
Author: My God,
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-01-08 13:08:38

To działało dla mnie, zwraca znacznik czasu w GMT!

    Date currDate;
    SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

    long currTime = 0;
    try {

        currDate = dateFormatLocal.parse( dateFormatGmt.format(new Date()) );
        currTime = currDate.getTime();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 2
Author: Bogdan,
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-25 12:46:16

Użyj tej klasy, aby uzyskać zawsze odpowiedni czas UTC z internetowego serwera NTP:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


class NTP_UTC_Time
{
private static final String TAG = "SntpClient";

private static final int RECEIVE_TIME_OFFSET = 32;
private static final int TRANSMIT_TIME_OFFSET = 40;
private static final int NTP_PACKET_SIZE = 48;

private static final int NTP_PORT = 123;
private static final int NTP_MODE_CLIENT = 3;
private static final int NTP_VERSION = 3;

// Number of seconds between Jan 1, 1900 and Jan 1, 1970
// 70 years plus 17 leap days
private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;

private long mNtpTime;

public boolean requestTime(String host, int timeout) {
    try {
        DatagramSocket socket = new DatagramSocket();
        socket.setSoTimeout(timeout);
        InetAddress address = InetAddress.getByName(host);
        byte[] buffer = new byte[NTP_PACKET_SIZE];
        DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);

        buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);

        writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET);

        socket.send(request);

        // read the response
        DatagramPacket response = new DatagramPacket(buffer, buffer.length);
        socket.receive(response);          
        socket.close();

        mNtpTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);            
    } catch (Exception e) {
      //  if (Config.LOGD) Log.d(TAG, "request time failed: " + e);
        return false;
    }

    return true;
}


public long getNtpTime() {
    return mNtpTime;
}


/**
 * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
 */
private long read32(byte[] buffer, int offset) {
    byte b0 = buffer[offset];
    byte b1 = buffer[offset+1];
    byte b2 = buffer[offset+2];
    byte b3 = buffer[offset+3];

    // convert signed bytes to unsigned values
    int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
    int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
    int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
    int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);

    return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
}

/**
 * Reads the NTP time stamp at the given offset in the buffer and returns 
 * it as a system time (milliseconds since January 1, 1970).
 */    
private long readTimeStamp(byte[] buffer, int offset) {
    long seconds = read32(buffer, offset);
    long fraction = read32(buffer, offset + 4);
    return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);        
}

/**
 * Writes 0 as NTP starttime stamp in the buffer. --> Then NTP returns Time OFFSET since 1900
 */    
private void writeTimeStamp(byte[] buffer, int offset) {        
    int ofs =  offset++;

    for (int i=ofs;i<(ofs+8);i++)
      buffer[i] = (byte)(0);             
}

}

I użyj go z:

        long now = 0;

        NTP_UTC_Time client = new NTP_UTC_Time();

        if (client.requestTime("pool.ntp.org", 2000)) {              
          now = client.getNtpTime();
        }

Jeśli potrzebujesz czasu UTC "teraz" jako DateTimeString użyj funkcji:

private String get_UTC_Datetime_from_timestamp(long timeStamp){

    try{

        Calendar cal = Calendar.getInstance();
        TimeZone tz = cal.getTimeZone();

        int tzt = tz.getOffset(System.currentTimeMillis());

        timeStamp -= tzt;

        // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
        DateFormat sdf = new SimpleDateFormat();
        Date netDate = (new Date(timeStamp));
        return sdf.format(netDate);
    }
    catch(Exception ex){
        return "";
     }
    } 

I użyj go z:

String UTC_DateTime = get_UTC_Datetime_from_timestamp(now);
 2
Author: Ingo,
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-07-30 22:14:00
public static void main(String args[]){
    LocalDate date=LocalDate.now();  
    System.out.println("Current date = "+date);
}
 2
Author: Arjun Singh,
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-19 11:21:44

Mówiąc prościej. Obiekt kalendarza przechowuje informacje o strefie czasowej, ale podczas wykonywania cal.getTime() wtedy informacja o strefie czasowej zostanie utracona. Więc dla konwersji strefy czasowej będę doradzał, aby użyć klas DateFormat...

 1
Author: Hitesh,
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-12-05 08:21:38

To moja realizacja:

public static String GetCurrentTimeStamp()
{
    Calendar cal=Calendar.getInstance();
    long offset = cal.getTimeZone().getOffset(System.currentTimeMillis());//if you want in UTC else remove it .
    return new java.sql.Timestamp(System.currentTimeMillis()+offset).toString();    
}
 1
Author: Gal Rom,
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-05-27 05:52:42

Jeśli chcesz uniknąć parsowania daty i po prostu chcesz znacznik czasu w GMT, możesz użyć:

final Date gmt = new Timestamp(System.currentTimeMillis()
            - Calendar.getInstance().getTimeZone()
                    .getOffset(System.currentTimeMillis()));
 1
Author: Matthias van der Vlies,
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-08-11 06:55:04
public class CurrentUtcDate 
{
    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println("UTC Time is: " + dateFormat.format(date));
    }
}

Wyjście:

UTC Time is: 22-01-2018 13:14:35

Możesz zmienić format daty w razie potrzeby.

 1
Author: santoshlokhande,
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
2018-07-04 03:51:06

Jeśli używasz czasu joda i chcesz mieć bieżący czas w milisekundach bez lokalnego offsetu możesz użyć tego:

long instant = DateTimeZone.UTC.getMillisKeepLocal(DateTimeZone.getDefault(), System.currentTimeMillis());
 0
Author: Managarm,
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-07-08 11:38:24

Aktualna data W UTC

Instant.now().toString().replaceAll("T.*", "");
 0
Author: Arefe,
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-03-04 07:52:52