Also read : Clock , time Zone in java 8, Display All TimeZone SORTED By name, TIME (or offset) in java 8
1) Create own LocalDate using LocalDate.of() method in java 8
/*
* Create own LocalDate using LocalDate.of() method
*/
import java.time.LocalDate;
import java.time.Month;
public class LocalDateExample_createCustom1 {
public static void main(String[] args) {
System.out.println("Create own/custom LocalDate");
LocalDate createOwnDate1 = LocalDate.of(2017, Month.JANUARY, 22); //Or
//LocalDate.of(2017, 1, 22)
System.out.println("createOwnDate = " + createOwnDate1);
LocalDate createOwnDate2 = LocalDate.of(2017, 1, 22);
System.out.println("createOwnDate2 = " + createOwnDate2);
//Create own LocalDate from STRING using parse method
//Create own LocalDate using parse method
String dateString = "2017-01-22";
LocalDate createOwnDate3 = LocalDate.parse(dateString);
System.out.println("createOwnDate3 = " + createOwnDate3);
}
}
/* OUTPUT
Create own/custom LocalDate
createOwnDate = 2017-01-22
createOwnDate2 = 2017-01-22
createOwnDate3 = 2017-01-22
*/
|
2) Create own LocalDate from STRING using parse method >
/*
* Create own LocalDate from STRING using parse method
*/
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class LocalDateExample_createCustom2 {
public static void main(String[] args) {
//1.1 Create own LocalDate from STRING
//Define date in string
String str = "2017-01-22";
//Define formatter
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//Now, use parse method to format date
LocalDate LocalDate1 = java.time.LocalDate.parse(str, dateTimeFormatter);
System.out.println("LocalDate1 = "+LocalDate1);
//1.2 Create own LocalDate from STRING
//Define date in string
String str2 = "22-01-2017";
//Define formatter
DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("dd-MM-yyyy");
//Now, use parse method to format date
LocalDate LocalDate2 = LocalDate.parse(str2, dateTimeFormatter2);
System.out.println("LocalDate2 = "+LocalDate2);
//To create formatted string from LocalDate object using format() method.
//Define formatter
DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate LocalDate3 = LocalDate.of(2017, 1, 22);
String formattedLocalDateInString = LocalDate3.format(dateTimeFormatter3);
System.out.println("formattedLocalDateInString = "+formattedLocalDateInString);
}
}
/* OUTPUT
LocalDate1 = 2017-01-22
LocalDate2 = 2017-01-22
formattedLocalDateInString = 2017-01-22
*/
|
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.