Java системное время миллисекунды

Java – Get time in milliseconds using Date, Calendar and ZonedDateTime

In this tutorial we will see how to get current time or given time in milliseconds in Java.
There are three ways to get time in milliseconds in java.
1) Using public long getTime() method of Date class.
2) Using public long getTimeInMillis() method of Calendar class
3) Java 8 – ZonedDateTime.now().toInstant().toEpochMilli() returns current time in milliseconds.

1. Getting current time in Milliseconds

In this example, we are getting the current time and then using the methods getTime() and getTimeInMillis(), which returns the Date time and Calendar time in milliseconds respectively. There is a simple way of doing the same in Java 8 using ZonedDateTime, I have shown that as a third way of getting time in millis in the Program.

import java.util.Calendar; import java.util.Date; import java.time.ZonedDateTime; public class Example < public static void main(String[] args) < //Getting the current date Date date = new Date(); //This method returns the time in millis long timeMilli = date.getTime(); System.out.println("Time in milliseconds using Date class: " + timeMilli); //creating Calendar instance Calendar calendar = Calendar.getInstance(); //Returns current time in millis long timeMilli2 = calendar.getTimeInMillis(); System.out.println("Time in milliseconds using Calendar: " + timeMilli2); //Java 8 - toEpochMilli() method of ZonedDateTime System.out.println("Getting time in milliseconds in Java 8: " + ZonedDateTime.now().toInstant().toEpochMilli()); >>
Time in milliseconds using Date class: 1508484583259 Time in milliseconds using Calendar: 1508484583267 Getting time in milliseconds in Java 8: 1508484583331

2. Get Time in Milliseconds for the Given date and time

In this example, we have given a date and time and we are displaying the given time in Milliseconds.

import java.util.Calendar; import java.util.Date; import java.text.SimpleDateFormat; import java.text.ParseException; public class Example < public static void main(String[] args) < //Specifying the pattern of input date and time SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); String dateString = "22-03-2017 11:18:32"; try< //formatting the dateString to convert it into a Date Date date = sdf.parse(dateString); System.out.println("Given Time in milliseconds : "+date.getTime()); Calendar calendar = Calendar.getInstance(); //Setting the Calendar date and time to the given date and time calendar.setTime(date); System.out.println("Given Time in milliseconds : "+calendar.getTimeInMillis()); >catch(ParseException e) < e.printStackTrace(); >> >
Given Time in milliseconds : 1490161712000 Given Time in milliseconds : 1490161712000

References:

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Читайте также:  Как сделать парсинг python

Class Date

Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a «leap second.» The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.

Some computer standards are defined in terms of Greenwich mean time (GMT), which is equivalent to universal time (UT). GMT is the «civil» name for the standard; UT is the «scientific» name for the same standard. The distinction between UTC and UT is that UTC is based on an atomic clock and UT is based on astronomical observations, which for all practical purposes is an invisibly fine hair to split. Because the earth’s rotation is not uniform (it slows down and speeds up in complicated ways), UT does not always flow uniformly. Leap seconds are introduced as needed into UTC so as to keep UTC within 0.9 seconds of UT1, which is a version of UT with certain corrections applied. There are other time and date systems as well; for example, the time scale used by the satellite-based global positioning system (GPS) is synchronized to UTC but is not adjusted for leap seconds. An interesting source of further information is the United States Naval Observatory (USNO):

Читайте также:  Css показать при наведении мыши

and the material regarding «Systems of Time» at:

which has descriptions of various different time systems including UT, UT1, and UTC.

  • A year y is represented by the integer y — 1900 .
  • A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
  • A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
  • An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12.
  • A minute is represented by an integer from 0 to 59 in the usual manner.
  • A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds and even then only in Java implementations that actually track leap seconds correctly. Because of the manner in which leap seconds are currently introduced, it is extremely unlikely that two leap seconds will occur in the same minute, but this specification follows the date and time conventions for ISO C.

In all cases, arguments given to methods for these purposes need not fall within the indicated ranges; for example, a date may be specified as January 32 and is interpreted as meaning February 1.

Constructor Summary

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date) .

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min) or GregorianCalendar(year + 1900, month, date, hrs, min) .

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec) .

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as «the epoch», namely January 1, 1970, 00:00:00 GMT.

Источник

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(), который определяется сопоставимым интерфейсом и реализуется по дате.

Форматирование даты с помощью 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); >> 

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

Источник

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