Java get current unix timestamp

java — Epoch or Unix timestamp and convert to from Date with examples

Epoch time is many seconds that already passed from 1 January 1970 UTC.

For a day, the total number of seconds is 24* 60*60 seconds. Epoch time returns the long number between the current time and 1 January 1970.

It is also called Epoch Unix time .

Every programming language provides API for handling Unix time. Java also provides a Date API for manipulation of Epoch Time.

The reason for 1970 is time in UNIX OS was introduced by taking this time.

EPOCH time = unix epoch time = Number of millseconds 01/01/1970 00:00:00

Epcoh/Unix time Examples in java

This tutorial talks about frequently used examples for manipulation of Epoch time in java.

  • Find epoch time in
  • Convert Date and time to milliseconds
  • Convert epoch time to LocalDate and LocalDateTime

How to get Epoch time or Unix timestamp in java?

Epoch time is a number of seconds that already passed since 1970 January 1 UTC. Prior to java8, Used System class to get Epoch time,

long epochTimeinSeconds = System.currentTimeMillis() / 1000L; System.out.println(epochTimeinSeconds); With java8, Date and Time API is improved and introduced java.time package for dealing with date, time, and zones over legacy classes.\ Instant is a class of points in a time zone.
long epochTimewithJava8 = Instant.now().getEpochSecond(); System.out.println(epochTimewithJava8); Both return the same output

How to convert Date and time to Epoch time seconds?

java.time.Instant class provides the toEpochMilli() method to convert the date with time into epoch milliseconds.

Here is a code for converting Date and time into epoch milliseconds

long epochTimewithJava81= Instant.now().toEpochMilli(); //Long = 1450879900184 System.out.println(epochTimewithJava81);

Convert epoch time java.time.LocalDateTime

LocalDateTime represents Date and time zone information, epoch time is in long seconds. For this, we need to have the System Default Timezone retrieved and the Instant object is required to convert to it.

long epochTimewithJava8 = System.currentTimeMillis(); System.out.println(epochTimewithJava8); Instant instant = Instant.ofEpochMilli(epochTimewithJava8); LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime(); System.out.println(localDateTime);

The output of the above java program is

 1535949786956 2018-09-03T10:13:06.956

Convert epoch time to LocalDate

LocalDate represents date only. To convert, Instant object creation is required with the default timezone.

long epochTimewithJava8 = System.currentTimeMillis(); System.out.println(epochTimewithJava8); Instant instant = Instant.ofEpochMilli(epochTimewithJava8); LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate(); System.out.println(localDate); Output is

String data is first converted to Date using SimpleDateFormat. The date format class accepts a formatted string and returns the Date object by calling the parse()method

String str="2018-09-03T04:51:00+05:0"; DateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); Date date=null; try  date = parser.parse(str); > catch (ParseException e)  // TODO Auto-generated catch block e.printStackTrace(); > System.out.println(date.getTime()/1000l); Output is
1535932260 You learned epoch milliseconds in java with examples and convert from/to date,localdate, and LocalDatetime from Unix milliseconds.

Источник

How to get the Unix timestamp in Java

How to get the Unix timestamp in Java

In the field of computer science, there is a concept of the unix timestamp, also known as the posix time or epoch time. This timestamp is defined as the number of seconds that have elapsed since January 1, 1970.

This is useful because it allows us to express dates and time in a single number as opposed to having to store the day, month, year, hour, minutes and seconds separately.

In this post, we’ll learn all the different ways to get the unix timestamp in Java.

Instant

Java introduced a new API for date and time to replace the old Date class. This is thread-safe and immutable, among other useful improvements.

Here’s how to get the current time in Java using the Instant class:

You can then take this number and convert it to a date and time using the Instant class:

With the Instant class, you can then call any method on the Instant class to get any additional piece of information that you want.

System.currentTimeMillis()

The original way to get the unix timestamp in Java was to use the System.currentTimeMillis() method. This method returns the number of milliseconds that have elapsed since the epoch time. From there you can just use simple division to get the number of seconds.

Remember that this is only useful for when you’re on Java 7 or lower, since in Java 8, you can use the much-improved Instant class.

Date

The final way to get the unix timestamp in Java is to use the Date class. This class is not thread-safe, and is not immutable, so only use it if you are on Java 7 or lower.

Here’s how to use the Date class to get the unix timestamp:

Conclusion

In this post, we explored three different ways to get the unix timestamp in Java.

Basically, if you are on a modern version of Java, you should use the Instant class, otherwise, you should use the Date class.

Hopefully, you’ve found this post helpful! Happy coding!

If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

Give feedback on this page , tweet at us, or join our Discord !

Источник

Java Unix time

Java Unix time tutorial shows how to compute Unix time in Java.

(also known as POSIX time or epoch time), is a system for describing a point in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, minus the number of leap seconds that have taken place since then.

Unix time is widely used on Unix-like operating systems but also in many other computing systems and file formats. It is often used by webmasters because a Unix timestamp can represent all time zones at once.

Unix timestamps should be stored as long numbers; if they are store as Java int values, then this leads to a 2038 year problem. 32-bit variables cannot encode times after 03:14:07 UTC on 19 January 2038.

We can use the date command to determine Unix time on Linux. Unix time can be determined on the https://www.unixtimestamp.com/.

Java Unix time example

The following example computes the Unix time.

package com.zetcode; import java.time.Instant; import java.util.Date; public class JavaUnixTimeEx < public static void main(String[] args) < long ut1 = Instant.now().getEpochSecond(); System.out.println(ut1); long ut2 = System.currentTimeMillis() / 1000L; System.out.println(ut2); Date now = new Date(); long ut3 = now.getTime() / 1000L; System.out.println(ut3); >>

There are three basic ways to compute Unix time in Java.

long ut1 = Instant.now().getEpochSecond(); System.out.println(ut1);

Since Java 8, it is possible to use Instant and its getEpochSecond to compute the Unix time.

long ut2 = System.currentTimeMillis() / 1000L; System.out.println(ut2);

Here we compute the Unix time with System.currentTimeMillis method. We need to transform milliseconds to seconds.

Date now = new Date(); long ut3 = now.getTime() / 1000L; System.out.println(ut3);

We can also use the old Date class to compute the Unix time.

In this article we have shown how to compute Unix time in Java.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Get Unix Timestamp in Java

As per wikipedia
Unix time is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00 UTC on 1 January 1970.

Unix time is standard way to describe point in time and used at multiple unix like operating system.

Ways to get unix timestamp in Java

There are multiple ways to get unix timestamp in Java.

Using Instant class

You can use Instant class to get unix timestamp in java in case you are using Java 8 or higher.

Using System.currentTimeMillis()

You can avoid date/Instant object creation and use System.currentTimeMillis() to get current time in millisecond. You can convert milliseconds to seconds by diving it by 1000L .

Using Date’s getTime() method

You can use legacy Date’s getTime() method to get unix timestamp in Java. You need to divide() time by 1000L to convert milliseconds to seconds.

Convert Date to unix timestamp in Java

Using Instant class

You can get Instant() from Date object using toInstant() method and get unix timestamp using getEpochSecond() .

You can also use LocalDate instead of java.util.Date . You need to first convert LocalDate to Instant and use getEpochSecond() to convert LocalDate to unix timestamp in Java.

Using Date’s getTime() method

You can use legacy Date’s getTime() method to convert Date to unixTimeStamp in Java. You need to divide() time by 1000L to convert milliseconds to seconds.

That’s all about how to get Get Unix Timestamp in Java.

Was this post helpful?

Share this

Author

Check if Date Is Between Two Dates in Java

Table of ContentsIntroductionDate & Local Date Class in JavaCheck if The Date Is Between Two Dates in JavaUsing the isAfter() and isBefore() Methods of the Local Date Class in JavaUsing the compareTo() Method of the Local Date Class in JavaUsing the after() and before() Methods of the Date Class in JavaUsing the compare To() Method […]

Find Difference Between Two Instant in Java

Table of ContentsWays to find difference between two Instant in JavaUsing Instant’s until() methodUsing ChronoUnit EnumUsing Duration’s between() method In this post, we will see how to find difference between two Instant in Java. Ways to find difference between two Instant in Java There are multiple ways to find difference between two Instant in various […]

Find Difference Between Two LocalDate in Java

Table of ContentsWays to find difference between two LocalDate in JavaUsing LocalDate’s until() methodUsing ChronoUnit EnumUsing Duration’s between() methodUsing Period’s between() methodFrequently asked questionsHow to find difference between two LocalDate in Java in Days?How to find difference between two LocalDate in Java in Years?How to find difference between two LocalDate in Java in Months?How to […]

Get List of Weekday Names in Java

Table of ContentsUsing DateFormatSymbols’s getWeekdays() methodUsing DateFormatSymbols’s getShortWeekdays() method [For short names]Using DateFormatSymbols’s getWeekdays() with Locale In this post, we will see how to get list of weekday names in Java. Using DateFormatSymbols’s getWeekdays() method We can use DateFormatSymbols’s getWeekdays() to get list of weekday names in Java. It will provide complete weekday names like […]

Get List of Month Names in Java

Table of ContentsUsing DateFormatSymbols’s getMonth() methodUsing DateFormatSymbols’s getShortMonths() method [ For short names]Using DateFormatSymbols’s getMonth() with Locale In this post, we will see how to get list of months name in Java. Using DateFormatSymbols’s getMonth() method We can use DateFormatSymbols’s getMonth() to get list of months in Java. It will provide complete month names like […]

Check if Date Is Weekend or Weekday in Java

Table of ContentsUsing LocalDate’s getDayOfWeek() methodUsing LocalDate with DayOfWeekUsing Date and Calendar classes In this post, we will see how to check if Date is weekend or weekday in Java. Please note that we will consider Saturaday/Sunday as weekend and rest five days of week as weekdays. Using LocalDate’s getDayOfWeek() method We can use LocalDate’s […]

Источник

Читайте также:  Python print any exception message
Оцените статью