Convert Java Date/Time to String & String back to Date/Time

#1. Why convert a Date to String & a String back to Date

(a) Convert a String input from say a file date, so that you can perform operations like

1) Adding 5 days to the date.
2) Comparing a date like before, after, equal, etc.

(b) Convert a Date back to String, so that you can represent the date in different formats like dd/MM/yyyy, dd/MMM/yyyy, yyyy-MM-dd, etc.

#2. Converting Java 8 LocalDate to String & String back to LocalDate

Output:

strNow=06/11/2015
dateNow=2015-11-06

#3. Converting Java 8 LocalDateTime to String & String back to LocalDateTime

Adding 5 days to now to demonstrate date operation on LocalDateTime .

Output:

strNowPlusFiveDays =11/11/2015 16:53:42
dateNowPlusFiveDays =2015-11-11T16:53:42

#4. Converting Java 8 LocalTime to String & String back to LocalTime

Setting the time to be “13:45:32”, and adding an hour to it.

Output:

strATimePlusAnHour=14:45:32
dateATimePlusAnHour=14:45:32

#5. Converting Java 8 LocalDateTime to ZoneDateTime and then to epoch milliseconds

The Epoch DateTime is: January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).

Output:

ldt=2015-05-24T18:41:16
zdt=2015-05-24T18:41:16+10:00[Australia/Sydney] millis=1432456876000

An Instant represents a point in time (similar to java.util.Date) with nanoseconds precision.

#6. Converting java.util.Date to Java 8 Instant

Output:

now = 2015-11-06T06:40:39.296Z
after 5 hours & 5 minutes = 2015-11-06T11:45:39.296Z
epochMilli = 1446810339296

#7. Converting java.util.Date to Java 8 LocalDate

Output:

date=2015-11-06

#8. Converting Java 8 LocalDateTime to java.util.Date

Output:

uitilDate=Fri Nov 06 18:02:14 AEDT 2015

Points to consider & pitfalls to avoid

1) The Java 8 DateFormatter, LocalDate, LocalDateTime, DateTimeFormatter, Instant, etc are immutable, hence thread-safe.

2) Since they are immutable, a common pitfall is when a new instance is created via the builder pattern methods like “plus”, they must be assigned to a new variable.

Wrong: line 2

Correct:

The “instant” is immutable, and hence the result from //2 creates a new object, and it must be assigned to a new variable “plus5Hr5Min”.

3) There are scenarios where the “TimeZone” must be considered. UTC stands for “Coordinated Universal Time”.

4) You may also need to keep “day light savings” into consideration. This is represented by the ZoneRules class.

If you change the “utcDateTime” from 2015-05-15 9:00am, to say 2015-01-15 9:00am or 2015-11-15 9:00am, then “laDaylightSavings” would return false.

Understanding TimeZones with examples in Java 8


Java & Big Data Interview FAQs

Java Key Areas Interview Q&As

800+ Java Interview Q&As

Java & Big Data Tutorials