Date in Java
Date In Java
Date and time are most important in coding. If we need to print today’s date, print today’s time, and we can import import java.time.LocalDate;
or import java.time.LocalTime;
package.
Display Current Date In Java
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
System.out.println("Local Date is "+date);
}
}
Display Current Time In Java
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println("Local Time is "+time);
}
}
Get Current Year In Java
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
System.out.println("Local Date is "+date);
// date.getYear will give us year in int type.
int currentYear = date.getYear();
System.out.println("Current Year is "+currentYear);
}
}
Method | Description |
---|---|
date.getYear(); | To get current year. for e.g 2022. |
date.getMonthValue(); | To get current month in number. for e.g 4 for april. |
date.getDayOfMonth(); | To get current month day in number. for e.g 5 for april 5. |
Display Both Date And Time In Java
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime datetime = LocalDateTime.now();
System.out.println("Current Datetime is "+ datetime);
}
}