Java current time millis to time

Class LocalTime

LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision. For example, the value «13:45.30.123456789» can be stored in a LocalTime .

This class does not store or represent a date or time-zone. Instead, it is a description of the local time as seen on a wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

The ISO-8601 calendar system is the modern civil calendar system used today in most of the world. This API assumes that all calendar systems use the same representation, this class, for time-of-day.

This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. The equals method should be used for comparisons.

Field Summary

Method Summary

Methods declared in class java.lang.Object

Field Details

MIN

MAX

The maximum supported LocalTime , ’23:59:59.999999999′. This is the time just before midnight at the end of the day.

MIDNIGHT

NOON

Method Details

now

Obtains the current time from the system clock in the default time-zone. This will query the system clock in the default time-zone to obtain the current time. Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.

now

Obtains the current time from the system clock in the specified time-zone. This will query the system clock to obtain the current time. Specifying the time-zone avoids dependence on the default time-zone. Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.

now

Obtains the current time from the specified clock. This will query the specified clock to obtain the current time. Using this method allows the use of an alternate clock for testing. The alternate clock may be introduced using dependency injection .

of

Obtains an instance of LocalTime from an hour and minute. This returns a LocalTime with the specified hour and minute. The second and nanosecond fields will be set to zero.

of

Obtains an instance of LocalTime from an hour, minute and second. This returns a LocalTime with the specified hour, minute and second. The nanosecond field will be set to zero.

of

Obtains an instance of LocalTime from an hour, minute, second and nanosecond. This returns a LocalTime with the specified hour, minute, second and nanosecond.

ofInstant

Obtains an instance of LocalTime from an Instant and zone ID. This creates a local time based on the specified instant. First, the offset from UTC/Greenwich is obtained using the zone ID and instant, which is simple as there is only one valid offset for each instant. Then, the instant and offset are used to calculate the local time.

Читайте также:  Python not like operator

ofSecondOfDay

Obtains an instance of LocalTime from a second-of-day value. This returns a LocalTime with the specified second-of-day. The nanosecond field will be set to zero.

ofNanoOfDay

Obtains an instance of LocalTime from a nanos-of-day value. This returns a LocalTime with the specified nanosecond-of-day.

from

Obtains an instance of LocalTime from a temporal object. This obtains a local time based on the specified temporal. A TemporalAccessor represents an arbitrary set of date and time information, which this factory converts to an instance of LocalTime . The conversion uses the TemporalQueries.localTime() query, which relies on extracting the NANO_OF_DAY field. This method matches the signature of the functional interface TemporalQuery allowing it to be used as a query via method reference, LocalTime::from .

parse

Obtains an instance of LocalTime from a text string such as 10:15 . The string must represent a valid time and is parsed using DateTimeFormatter.ISO_LOCAL_TIME .

parse

Obtains an instance of LocalTime from a text string using a specific formatter. The text is parsed using the formatter, returning a time.

isSupported

  • NANO_OF_SECOND
  • NANO_OF_DAY
  • MICRO_OF_SECOND
  • MICRO_OF_DAY
  • MILLI_OF_SECOND
  • MILLI_OF_DAY
  • SECOND_OF_MINUTE
  • SECOND_OF_DAY
  • MINUTE_OF_HOUR
  • MINUTE_OF_DAY
  • HOUR_OF_AMPM
  • CLOCK_HOUR_OF_AMPM
  • HOUR_OF_DAY
  • CLOCK_HOUR_OF_DAY
  • AMPM_OF_DAY

If the field is not a ChronoField , then the result of this method is obtained by invoking TemporalField.isSupportedBy(TemporalAccessor) passing this as the argument. Whether the field is supported is determined by the field.

isSupported

  • NANOS
  • MICROS
  • MILLIS
  • SECONDS
  • MINUTES
  • HOURS
  • HALF_DAYS

If the unit is not a ChronoUnit , then the result of this method is obtained by invoking TemporalUnit.isSupportedBy(Temporal) passing this as the argument. Whether the unit is supported is determined by the unit.

range

Gets the range of valid values for the specified field. The range object expresses the minimum and maximum valid values for a field. This time is used to enhance the accuracy of the returned range. If it is not possible to return the range, because the field is not supported or for some other reason, an exception is thrown. If the field is a ChronoField then the query is implemented here. The supported fields will return appropriate range instances. All other ChronoField instances will throw an UnsupportedTemporalTypeException . If the field is not a ChronoField , then the result of this method is obtained by invoking TemporalField.rangeRefinedBy(TemporalAccessor) passing this as the argument. Whether the range can be obtained is determined by the field.

get

Gets the value of the specified field from this time as an int . This queries this time for the value of the specified field. The returned value will always be within the valid range of values for the field. If it is not possible to return the value, because the field is not supported or for some other reason, an exception is thrown. If the field is a ChronoField then the query is implemented here. The supported fields will return valid values based on this time, except NANO_OF_DAY and MICRO_OF_DAY which are too large to fit in an int and throw an UnsupportedTemporalTypeException . All other ChronoField instances will throw an UnsupportedTemporalTypeException . If the field is not a ChronoField , then the result of this method is obtained by invoking TemporalField.getFrom(TemporalAccessor) passing this as the argument. Whether the value can be obtained, and what the value represents, is determined by the field.

getLong

Gets the value of the specified field from this time as a long . This queries this time for the value of the specified field. If it is not possible to return the value, because the field is not supported or for some other reason, an exception is thrown. If the field is a ChronoField then the query is implemented here. The supported fields will return valid values based on this time. All other ChronoField instances will throw an UnsupportedTemporalTypeException . If the field is not a ChronoField , then the result of this method is obtained by invoking TemporalField.getFrom(TemporalAccessor) passing this as the argument. Whether the value can be obtained, and what the value represents, is determined by the field.

Читайте также:  focus

Источник

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.

Источник

Format Milliseconds Duration to Hours, Minutes and Seconds

Learn to convert a given duration in milliseconds to hours, minutes and seconds; and format to HH:mm:ss or any other custom pattern.

If we know the arithmetic formulas to calculate the hours, minutes or seconds from a given amount of milliseconds then we can use the Duration class methods and apply those calculations ourselves.

Duration class models a quantity or amount of time in terms of seconds and nanoseconds. It provides methods for other duration-based time units such as toHours() , toMinutes () and getSeconds() . We can use these methods to get time in the specific unit and get the modulo to extract the exact amount.

long millis = 54321000; Duration duration = Duration.ofMillis(millis); long h = duration.toHours(); long m = duration.toMinutes() % 60; long s = duration.getSeconds() % 60; String timeInHms = String.format("%02d:%02d:%02d", h, m, s); System.out.println(timeInHms); //15:05:21

2. Apache Common’s DurationFormatUtils

Читайте также:  All about shadow java

The DurationFormatUtils class provides formatting utilities and constants. Its formatDuration(durationMillis, format) method can be used to format the specified duration in a specified format.

It takes an optional third parameter padWithZeros that specifies whether to pad the left-hand side of numbers with 0’s. For example, if we want to write ‘5’ to ’05’ then we should pass the third argument as true .

long millis = 54321000; String timeInHms = DurationFormatUtils .formatDuration(millis, "HH:mm:ss", true); System.out.println(timeInHms); //15:05:21 //Without padding timeInHms = DurationFormatUtils .formatDuration(millis, "HH:mm:ss", false); System.out.println(timeInHms); //15:5:21

To use this class, include the latest version of commons-lang from Maven repository.

 org.apache.commons commons-lang3 3.12.0 

In this short Java tutorial, we learned to convert a given duration in milliseconds to a formatted string containing hours, minutes and seconds. This information can be useful in printing the logs for long-running jobs where jobs may be running for hours.

Источник

How To Measure Elapsed Time in Java

Learn to calculate execution time or measure elapsed time of a program or some Java statements using various techniques pre and post Java 8 release.

1. Measuring Elapsed Time since Java 8

If we’re using Java 8 – we can try the new java.time.Instant and java.time.Duration classes. Below Java 8, proceed to the next method down in the article.

To get the elapsed execution time in different time units, use the following method. It measures the duration between two Instants. And Instant represents the time elapsed since the epoch.

long timeElapsed = Duration.between(startInstant, finishInstant).toMillis();
import java.text.ParseException; import java.util.concurrent.TimeUnit; public class Main < public static void main(String[] args) throws ParseException < Instant start = Instant.now(); //Measure execution time for this method methodToTime(); Instant finish = Instant.now(); long timeElapsed = Duration.between(start, finish).toMillis(); //in millis >private static void methodToTime() < try < TimeUnit.SECONDS.sleep(3); >catch (InterruptedException e) < e.printStackTrace(); >> >

This is the most recommended solution to measure elapsed time in Java. It provides nanoseconds level precision of elapsed time between two measurements. It is the most preferred approach to calculate thread execution time in Java.

import java.text.ParseException; import java.util.concurrent.TimeUnit; public class Main < public static void main(String[] args) throws ParseException < long startTime = System.nanoTime(); methodToTime(); //Measure execution time for this method long endTime = System.nanoTime(); long durationInNano = (endTime - startTime); //Total execution time in nano seconds //Same duration in millis long durationInMillis = TimeUnit.NANOSECONDS.toMillis(durationInNano); //Total execution time in nano seconds System.out.println(durationInNano); System.out.println(durationInMillis); >private static void methodToTime() < try < TimeUnit.SECONDS.sleep(3); >catch (InterruptedException e) < e.printStackTrace(); >> >
3000076434 //More precise 3000

If you are not too concerned about nano level precision, or unfortunately still stuck in legacy Java versions – You shall be using System.currentTimeMillis() method.

import java.text.ParseException; import java.util.concurrent.TimeUnit; public class Main < public static void main(String[] args) throws ParseException < long startTime = System.currentTimeMillis(); methodToTime(); //Measure execution time for this method long endTime = System.currentTimeMillis(); long duration = (endTime - startTime); //Total execution time in milli seconds System.out.println(duration); >private static void methodToTime() < try < TimeUnit.SECONDS.sleep(3); >catch (InterruptedException e) < e.printStackTrace(); >> >

We can convert the above time in Millis to other time units such as hours, minutes and seconds to measure execution time in corresponding time units.

Источник

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