xxxxxxxxxx
import java.time.LocalDateTime;
// https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html
public class LocalDateTimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
System.out.println("yr:" + year
+ " mth:" + month
+ " day:" + day
+ " hr:" + hour
+ " min:" + minute
+ " sec:" + second);
}
}
xxxxxxxxxx
// Import required packages
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
// Convert LocalDateTime to Date
LocalDateTime localDateTime = LocalDateTime.now();
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
xxxxxxxxxx
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
xxxxxxxxxx
package br.com.dicasdejava.fundamentos;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class FormatarLocalDate {
public static void main(String[] args) {
//Obtém LocalDate de hoje
LocalDate hoje = LocalDate.now();
System.out.println("LocalDate antes de formatar: " + hoje);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String hojeFormatado = hoje.format(formatter);
System.out.println("LocalDate depois de formatar: " + hojeFormatado);
//Obtém LocalDateTime de agora
LocalDateTime agora = LocalDateTime.now();
System.out.println("LocalDateTime antes de formatar: " + agora);
formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
String agoraFormatado = agora.format(formatter);
System.out.println("LocalDateTime depois de formatar: " + agoraFormatado);
}
}
xxxxxxxxxx
import java.time.LocalTime;
public class LocalTimeExample1 {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println(time);
}
}