#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
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.mytutorial; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class Convert { public static void main(String[] args) { String datePattern = "dd/MM/yyyy"; DateTimeFormatter df = DateTimeFormatter.ofPattern(datePattern); //Convert from LocalDate to String LocalDate now = LocalDate.now(); String strNow = df.format(now); System.out.println("strNow=" + strNow); //Convert from String to LocalDate LocalDate dateNow = LocalDate.parse(strNow, df); System.out.println("dateNow=" + dateNow); } } |
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 .
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.mytutorial; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; public class Convert { public static void main(String[] args) { String datePattern = "dd/MM/yyyy HH:mm:ss "; DateTimeFormatter df = DateTimeFormatter.ofPattern(datePattern); //Convert from LocalDateTime to String LocalDateTime now = LocalDateTime.now(); LocalDateTime nowPlusFiveDays = now.plus(5, ChronoUnit.DAYS); String strNowPlusFiveDays = df.format(nowPlusFiveDays); System.out.println("strNowPlusFiveDays =" + strNowPlusFiveDays); //Convert from String to LocalDateTime LocalDateTime dateNowPlusFiveDays = LocalDateTime.parse(strNowPlusFiveDays, df); System.out.println("dateNowPlusFiveDays =" + dateNowPlusFiveDays); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.mytutorial; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; public class Convert { public static void main(String[] args) { String datePattern = "HH:mm:ss "; DateTimeFormatter df = DateTimeFormatter.ofPattern(datePattern); //Convert from LocalTime to String LocalTime aTime = LocalTime.of(13, 45, 32); LocalTime aTimePlusAnHour = aTime.plus(1, ChronoUnit.HOURS); String strATimePlusAnHour = df.format(aTimePlusAnHour); System.out.println("strATimePlusAnHour=" + strATimePlusAnHour); //Convert from String to LocalTime LocalTime dateATimePlusAnHour = LocalTime.parse(strATimePlusAnHour, df); System.out.println("dateATimePlusAnHour=" + dateATimePlusAnHour); } } |
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).
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.mytutorial; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; public class Convert { public static void main(String[] args) { LocalDateTime ldt = LocalDateTime.of(2015, 5, 24, 18, 41, 16); ZonedDateTime zdt = ldt.atZone(ZoneId.of("Australia/Sydney")); long millis = zdt.toInstant().toEpochMilli(); System.out.println("ldt=" + ldt); System.out.println("zdt=" + zdt); System.out.println("millis=" + millis); } } |
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
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.mytutorial; import java.time.Duration; import java.time.Instant; import java.util.Date; public class Convert { public static void main(String[] args) { Instant instant = Instant.ofEpochMilli(new Date().getTime()); System.out.println("now = " + instant); // Adding 5 hours and 5 minutes to an Instant Instant plus5Hr5Min = instant.plus(Duration.ofHours(5).plusMinutes(5)); // immutable, hence assign System.out.println("after 5 hours & 5 minutes = " + plus5Hr5Min); long epochMilli = plus5Hr5Min.toEpochMilli(); System.out.println("epochMilli = " + epochMilli); } } |
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
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.mytutorial; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; public class Convert { public static void main(String[] args) { Date input = new Date(); LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); System.out.println("date=" + date); } } |
Output:
date=2015-11-06
#8. Converting Java 8 LocalDateTime to java.util.Date
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.mytutorial; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; public class Convert { public static void main(String[] args) { LocalDateTime date = LocalDateTime.now(); Date uitilDate = Date.from(date.atZone(ZoneId.systemDefault()).toInstant()); System.out.println("uitilDate=" + uitilDate); } } |
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
|
1 2 3 4 |
Instant instant = Instant.ofEpochMilli(new Date().getTime()); //1 instant.plus(Duration.ofHours(5).plusMinutes(5)); //2 |
Correct:
|
1 2 3 4 |
Instant instant = Instant.ofEpochMilli(new Date().getTime()); //1 Instant plus5Hr5Min = instant.plus(Duration.ofHours(5).plusMinutes(5)); //2 immutable, hence assign |
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”.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package test; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; public class Converting { public static void main(String[] args) { // 2015-05-15 9:00am LocalDateTime utcDateTime = LocalDateTime.of(2015, 05, 15, 9, 0); ZoneId zoneLA = ZoneId.of("America/Los_Angeles"); ZoneId zoneBerlin = ZoneId.of("Europe/Berlin"); ZonedDateTime _9AmInLA = ZonedDateTime.of(utcDateTime, zoneLA); ZonedDateTime _9AmInBerlin = ZonedDateTime.of(utcDateTime, zoneBerlin); //........ } } |
4) You may also need to keep “day light savings” into consideration. This is represented by the ZoneRules class.
|
1 2 3 4 5 6 7 8 |
boolean laDaylightSavings = zoneLA.getRules().isDaylightSavings(_9AmInLA.toInstant()); boolean berlinDaylightSavings = zoneBerlin.getRules().isDaylightSavings(_9AmInBerlin.toInstant()); System.out.println("laDaylightSavings=" + laDaylightSavings); //true System.out.println("berlinDaylightSavings=" + berlinDaylightSavings); //true |
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.