java localdatetime code example
Example 1: format localdate java
LocalDate today = LocalDate.now();
String formattedDate = today.format(DateTimeFormatter.ofPattern("dd-MMM-yy"));
System.out.println(formattedDate);
Example 2: localdatetime java example
LocalDateTime current=LocalDateTime.now();
LocalDateTime dateTime=LocalDateTime.of(year,month,day,hour,minute,second);
dateTime.getHour();
dateTime.getDayOfWeek();
dateTime.isBefore(someOtherDateTime);
dateTime.toLocalDate();
dateTime.toLocalTime();
Example 3: java instant to localdatetime
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
Example 4: java new localdatetime
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
public class Java8Demo {
public static void main(String args[]) {
LocalDateTime rightNow = LocalDateTime.now();
System.out.println("current datetime : " + rightNow);
LocalDateTime aDateTime = LocalDateTime.of(2015,
Month.JULY, 29, 19, 30, 40);
System.out.println("some datetime : " + aDateTime);
LocalDate currentDate = LocalDate.now();
LocalTime currentTime = LocalTime.now();
LocalDateTime fromDateAndTime = LocalDateTime.of(currentDate,
currentTime);
System.out.println("LocalDateTime created by combining LocalDate"
+ " and LocalTime" + fromDateAndTime);
LocalDate retrievedDate = fromDateAndTime.toLocalDate();
LocalTime retrievedTime = fromDateAndTime.toLocalTime();
System.out.println("retreived LocalDate : " + retrievedDate);
System.out.println("retreived LocalTime : " + retrievedTime);
}
}
Output :
current datetime : 2015-08-02T00:29:53.949
some datetime : 2015-07-29T19:30:40
LocalDateTime created by combining LocalDate
and LocalTime2015-08-02T00:29:53.949
retreived LocalDate : 2015-08-02
retreived LocalTime : 00:29:53.949