Java дата по гринвичу

17. Java – Дата и время

Java предоставляет класс Date, который доступен в пакете java.util, этот класс заключает в себе текущую дату и время.

Конструкторы

Класс Date поддерживает два конструктора, которые показаны ниже.

Конструктор и описание
1 Date()
Этот конструктор инициализирует объект с текущей датой и временем.
2 Date(long millisec)
Этот конструктор принимает аргумент равный числу миллисекунд, истекших с полуночи 1 января 1970 г.

Методы класса Date

Ниже представлены методы класса Date.

Методы с описанием
1 boolean after(Date date)
Возвращает значение true, если вызывающий объект date содержит дату, которая раньше заданной даты, в противном случае он возвращает значение false.
2 boolean before(Date date)
Возвращает значение true, если вызывающий объект date содержит дату, более раннюю, чем заданная дата, в противном случае он возвращает значение false.
3 Object clone()
Дублирование вызывающего объекта date.
4 int compareTo(Date date)
Сравнивает значение вызывающего объекта с этой датой. Возвращает 0, если значения равны. Возвращает отрицательное значение, если объект вызова является более ранним, чем дата. Возвращает положительное значение, если объект вызова позже даты.
5 int compareTo(Object obj)
Работает точно так же compareTo(Date), если объект вызова имеет класс Date. В противном случае вызывает ClassCastException.
6 boolean equals(Object date)
Возвращает значение true, если вызывающий объект date содержит то же время и дату, которая указана в date, в противном случае он возвращает значение false.
7 long getTime()
Возвращает количество миллисекунд, истекших с 1 января 1970 года.
8 int hashCode()
Возвращает хэш-код для вызывающего объекта.
9 void setTime(long time)
Задает дату и время, соответствующие моменту времени, что представляет собой общее затраченное время в миллисекундах от полуночи 1 января 1970 года.
10 String toString()
Преобразует вызывающий объект date в строку и возвращает результат.

Текущая дата и время в Java

Получить текущую дату и время в Java достаточно не трудно. Вы можете использовать простой объект date вместе с методом toString(), чтобы вывести текущую дату и время следующим образом:

import java.util.Date; public class Test < public static void main(String args[]) < // Инициализация объекта date Date date = new Date(); // Вывод текущей даты и времени с использованием toString() System.out.println(date.toString()); >> 

Получим следующий результат:

Sun Nov 13 00:14:19 FET 2016 

Сравнение дат

Существуют три способа в Java сравнить даты:

  • Можно использовать функцию getTime(), чтобы получить количество миллисекунд, прошедших с момента полуночи 1 января 1970, для обоих объектов, а затем сравнить эти два значения.
  • Вы можете использовать методы before(), after() и equals(). Поскольку 12 число месяца раньше 18 числа, например, new Date(99, 2, 12).before(new Date (99, 2, 18)) возвращает значение true.
  • Можно использовать метод compareTo(), который определяется сопоставимым интерфейсом и реализуется по дате.
Читайте также:  Обход двоичного дерева java

Форматирование даты с помощью SimpleDateFormat

SimpleDateFormat – это конкретный класс для парсинга и форматирования даты в Java. SimpleDateFormat позволяет начать с выбора любых пользовательских шаблонов для форматирования даты и времени. Например:

import java.util.*; import java.text.*; public class Test < public static void main(String args[]) < Date dateNow = new Date(); SimpleDateFormat formatForDateNow = new SimpleDateFormat("E yyyy.MM.dd 'и время' hh:mm:ss a zzz"); System.out.println("Текущая дата " + formatForDateNow.format(dateNow)); >> 

Получим следующий результат:

Текущая дата Вс 2016.11.13 и время 12:12:36 AM FET 

Формат-коды SimpleDateFormat

Для того, чтобы задать в Java формат даты и времени, используйте строковый шаблон (регулярные выражения) с датой и временем. В этой модели все буквы ASCII зарезервированы как шаблон письма, которые определяются следующим образом:

Символ Описание Пример
G Обозначение эры н.э.
y Год из четырех цифр 2016
M Номер месяца года 11
d Число месяца 13
h Формат часа в A.M./P.M.(1~12) 7
H Формат часа(0~23) 19
m Минуты 30
s Секунды 45
S Миллисекунды 511
E День недели Вс
D Номер дня в году 318
F Номер дня недели в месяце 2 (второе воскресение в этом месяце)
w Номер неделя в году 46
W Номер недели в месяце 2
a Маркер A.M./P.M. AM
k Формат часа(1~24) 24
K Формат часа в A.M./P.M.(0~11) 0
z Часовой пояс FET (Дальневосточноевропейское время)
Выделение для текста Текст
» Одинарная кавычка

Форматирование даты с помощью printf

Формат даты и времени можно сделать без труда с помощью метода printf. Вы используете формат двух букв, начиная с t и заканчивая одним из символов в таблице, приведенных ниже. Например:

import java.util.Date; public class Test < public static void main(String args[]) < // Инициализация объекта date Date date = new Date(); // Вывод текущей даты и времени с использованием toString() String str = String.format("Текущая дата и время: %tc", date); System.out.printf(str); >> 

Получим следующий результат:

Текущая дата и время: Вс ноя 13 00:55:59 FET 2016 

Было бы немного глупо, если Вы должны были бы поставить дату несколько раз для форматирования каждой части. По этой причине формат строки может указывать индекс аргумента для форматирования.

Индекс должен непосредственно следовать за % и завершаться $. Например:

import java.util.Date; public class Test < public static void main(String args[]) < // Инициализация объекта date Date date = new Date(); // Вывод текущей даты с использованием toString() System.out.printf("%1$s %2$td %2$tB %2$tY", "Дата:", date); >> 

Получим следующий результат:

Источник

Get GMT Time in Java

But the date is always is interpreted in my local time zone. What am I doing wrong and how can I convert a java Date to GMT?

FYI, the terribly troublesome old date-time classes such as java.util.Date , java.util.Calendar , and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

12 Answers 12

Odds are good you did the right stuff on the back end in getting the date, but there’s nothing to indicate that you didn’t take that GMT time and format it according to your machine’s current locale.

final Date currentTime = new Date(); final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z"); // Give it to me in GMT time. sdf.setTimeZone(TimeZone.getTimeZone("GMT")); System.out.println("GMT time: " + sdf.format(currentTime)); 

The key is to use your own DateFormat, not the system provided one. That way you can set the DateFormat’s timezone to what you wish, instead of it being set to the Locale’s timezone.

Читайте также:  Python tasks and coroutines

long millis = System.currentTimeMillis(); will return the number of milliseconds that have elapsed since 1 January 1970, 00:00:00.000 UTC . UTC time is what most people really want when they say «GMT time». java.util.Date has a getTime() method which does the same thing for an arbitrary Date . You might need to use a java.util.Calendar to construct the Date object depending on your needs, if so Calendar’s getTime() method will return a Date which you can then getTime() to get the milliseconds offset.

I wonder why no one does this:

Calendar time = Calendar.getInstance(); time.add(Calendar.MILLISECOND, -time.getTimeZone().getOffset(time.getTimeInMillis())); Date date = time.getTime(); 

Update: Since Java 8,9,10 and more, there should be better alternatives supported by Java. Thanks for your comment @humanity

FYI, the terribly troublesome old date-time classes such as java.util.Date , java.util.Calendar , and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

From my experience, the bundled Calendar and Date classes in Java can yield undersired effect. If you wouldn’t mind upgrading to Java 8, then consider using ZonedDateTime

ZonedDateTime currentDate = ZonedDateTime.now( ZoneOffset.UTC ); 

tl;dr

java.time

The Answer by Damilola is correct in suggesting you use the java.time framework built into Java 8 and later. But that Answer uses the ZonedDateTime class which is overkill if you just want UTC rather than any particular time zone.

The troublesome old date-time classes are now legacy, supplanted by the java.time classes.

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now() ; 

You can think of Instant as the building block to which you can add a time zone ( ZoneID ) to get a ZonedDateTime .

ZoneId z = ZoneId.of( "America/Montreal" ); ZonedDateTime zdt = instant.atZone( z ); 

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more.

    You can achieve it using Java 8 java.time package

    Get current GMT time in Java:

    ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneOffset.UTC); System.out.println("Print current time in GMT: "+zonedDateTime); // 2021-08-30T03:58:05.815942377Z 

    Convert a java.util.Date to GMT

    // use a formatter DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss O"); Date date = new Date(); //; java.util.Date object Instant instant = date.toInstant(); ZonedDateTime zonedDateTime = instant.atZone(ZoneOffset.UTC); System.out.println("java.util.Date to GMT: "+customFormatter.format(zonedDateTime)); // 08/30/2021 03:58:05 GMT 

    Ref

    After trying a lot of methods, I found out, to get the time in millis at GMT you need to create two separate SimpleDateFormat objects, one for formatting in GMT and another one for parsing.

     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); format.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = new Date(); SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date dateTime= dateParser.parse(format.format(date)); long gmtMilliSeconds = dateTime.getTime(); 

    To get the time in millis at GMT all you need is

    long millis = System.currentTimeMillis(); 

    While the following work, they are inefficient. You can also do

    long millis = new Date().getTime(); 
    long millis = Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis(); 

    this answer is incorrect. Tried printing new Date(millis) from long millis = Calendar.getInstance(TimeZone.getTimeZone(«GMT»)).getTimeInMillis(); It still gives current time zone time.

    You can’t

    First, you are asking the impossible. An old-fashioned Date object hasn’t got, as in cannot have a time zone or GMT offset.

    But the date is always is interpreted in my local time zone.

    I suppose that you have printed the Date or done something else that implicitly calls it toString method. I believe that this is the only time that the Date is interpreted in your time zone. More precisely in the current default time zone of your JVM. On the other hand this is unavoidable. Date.toString() does behave in that way, it picks up the JVM’s time zone setting and uses it for rendering the string to be returned.

    You can with java.time

    You shouldn’t use a Date , though. That class is poorly designed and fortunately long outdated. Also java.time, the modern Java date and time API that replaces it, has a class or two for dates and times with offset from GMT or UTC. I am considering GMT and UTC synonymous for now, strictly speaking they are not.

     OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC); System.out.println("Time now in UTC (GMT) is " + now); 

    When I ran this snippet just now, the output was:

    Time now in UTC (GMT) is 2019-06-17T11:51:38.246188Z

    The trailing Z of the output means UTC.

    Источник

Оцените статью