In this article, we’ll share some basic DateTime conversion by using DateTime API of Java 8 that you would need in a project. Working with Dates, trying to convert them into the proper format is always a pain in the ass. After Java 8, a new DateTime API is introduced.

We’ll basically work on examples.

Get Current TimeStamp as Ms or Sec

You need to use Instant object to get the timestamp. You can get the timestamp as milliseconds or second.

Output: 1549057795923

Output: 1549057795

Get Local Date by TimeZone

You can use LocalDate object to get the current system date. You are able to pass ZoneId object to change the time zone.

Output:

According to the hour that you run that code, you might have the same result or a different one. As a one-time zone might have started to live the next already 🙂

GMT+2 2019-02-01
GMT+5 2019-02-02

Get X Days/Months/Year Early or Later

There are very handy methods coming with LocalDate object. You can add, subtract days, months, years or even week to a given date and get the new date object.

Output:

Today 2019-02-02
Past 2019-01-30
Future 2019-02-05

Output:

Today 2019-02-02
Past 2018-11-02
Future 2019-05-02

You can also add or subtract week or year with other methods.

LocalDateTime to TimeStamp

You might need to convert a date object to timestamp. Here’s how you can achieve this challenge.

Output: TimeStamp is 1549882173000

DateTime Formatting

Output: Today 2019-02-02 08:55:47.208

Example Formats:

TimeStamp to DateTime 

Output: Formatted Date 2019-02-02 09:33:33.084

String to Date

Output: Parsed Date 1985-08-26

String to TimeStamp

Output: String to TimeStamp 1543336200212

Hope those will help when you need to deal with Dates. In case you encounter any problems and questions, just let us know by commenting so we add new examples.

Happy Testing!