localdate java 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();//gets current LocalDateTime
LocalDateTime dateTime=LocalDateTime.of(year,month,day,hour,minute,second);//gets specific LocalDateTime
dateTime.getHour();//get the hour of a DateTime
dateTime.getDayOfWeek();//get number of current day in week
dateTime.isBefore(someOtherDateTime);//checks if it is before another LocalDateTime
dateTime.toLocalDate();//converts it to a LocalDate
dateTime.toLocalTime();//converts it to a LocalTime

Example 3: java instant to localdatetime

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

// ...

//Convert instant to LocalDateTime, no timezone, add a zero offset / UTC+0
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

Example 4: java date to localdate

LocalDate localDate = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(date) );

Tags:

Java Example