java string to localdatetime code example
Example 1: convert string to localdatetime
String str = "2016-03-04 11:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
Example 2: java 8 string to localdate
package com.mkyong.date;
import java.time.LocalDate;
public class JavaDateExample1 {
public static void main(String[] args) {
String date = "2016-08-16";
LocalDate localDate = LocalDate.parse(date);
System.out.println(localDate);
}
}
Copy
Example 3: how to turna date into a LocalDateTime java
public LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
Example 4: how to turna date into a LocalDateTime java
public LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) {
return Instant.ofEpochMilli(dateToConvert.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
Example 5: formatting specific date and time in localdatetime
String dateTime = "1995-07-25 15:03:45";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = LocalDateTime.parse(dateTime, dateTimeFormatter);