Also read : Create own LocalDate, Clock , time Zone in java 8, Display All TimeZone SORTED By name, TIME (or offset) in java 8
1) Create own LocalDateTime using LocalDateTime.of() method
import java.time.LocalDateTime;
import java.time.Month;
/**
* Create own LocalDateTime using LocalDateTime.of() method
*/
public class LocalDateTimeExample_createCustom1 {
public static void main(String[] args) {
//Year, Month, dayOfMonth, hour, minute, second
LocalDateTime createOwnDateTime1 = LocalDateTime.of(2017, Month.JANUARY, 22, 19, 55, 56);
System.out.println("createOwnDateTime1 = " + createOwnDateTime1);
//Year, Month, dayOfMonth, hour, minute, second
LocalDateTime createOwnDateTime2 = LocalDateTime.of(2017, 1, 22, 19, 55, 56);
System.out.println("createOwnDateTime2 = " + createOwnDateTime2);
//Create own LocalDateTime from STRING using parse method
String dateString = "2017-01-22T19:55:56";
LocalDateTime createOwnDateTime3 = LocalDateTime.parse(dateString);
System.out.println("createOwnDateTime3 = " + createOwnDateTime3);
}
}
/* OUTPUT
createOwnDateTime1 = 2017-01-22T19:55:56
createOwnDateTime2 = 2017-01-22T19:55:56
createOwnDateTime3 = 2017-01-22T19:55:56
*/
|
2) Create own LocalDateTime from STRING using parse method >
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Create own LocalDateTime from STRING
*/
public class LocalDateTimeExample_createCustom2 {
public static void main(String[] args) {
//1.1 Create own LocalDateTime from STRING
//Define date in string
String str1 = "2017-01-22 19:55:56";
//Define formatter
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//Now, use parse method to format date
LocalDateTime localDateTime1 = LocalDateTime.parse(str1, dateTimeFormatter1);
System.out.println("localDateTime1 = "+localDateTime1);
//1.2 Create own LocalDateTime from STRING
//Define date in string
String str2 = "22-01-2017 19:55:56";
//Define formatter
DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
//Now, use parse method to format date
LocalDateTime localDateTime2 = LocalDateTime.parse(str2, dateTimeFormatter2);
System.out.println("localDateTime2 = "+localDateTime2);
//To create formatted string from LocalDateTime object using format() method.
//Define formatter
DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime3 = LocalDateTime.of(2017, 1, 22, 19, 55, 56);
String formattedLocalDateTimeInString = localDateTime3.format(dateTimeFormatter3);
System.out.println("formattedLocalDateTimeInString = "+formattedLocalDateTimeInString);
}
}
/* OUTPUT
localDateTime1 = 2017-01-22T19:55:56
localDateTime2 = 2017-01-22T19:55:56
formattedLocalDateTimeInString = 2017-01-22 19:55:56
*/
|
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.