package my_proj;
import java.time.LocalDate;
public class my_first {
public static void main(String[] args) {
LocalDate my_date = LocalDate.now(); // date object is created
System.out.println(my_date); // 2020-02-14
}
}
Different Date and time Classes we will use
LocalDate : Class representing Date ( yyyy-MM-dd)
LocalTime : Class representing Time ( HH-mm-ss-zzz )
LocalDateTime : Class representing Date and time (yyyy-MM-dd-HH-mm-ss.zzz)
DateTimeFormatter : Formatter for displaying date and time
Displaying present time
package my_proj;
import java.time.LocalTime;
public class my_first {
public static void main(String[] args) {
LocalTime my_time = LocalTime.now(); // time object is created
System.out.println(my_time); // 08:59:47.991582400
}
}
Both date and time
package my_proj;
import java.time.LocalDateTime;
public class my_first {
public static void main(String[] args) {
LocalDateTime my_date_time = LocalDateTime.now(); // object
System.out.println(my_date_time); // 2020-02-15T09:11:33.331329600
}
}
Using DateTimeFormatter
package my_proj;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class my_first {
public static void main(String[] args) {
LocalDateTime my_date_time = LocalDateTime.now();
System.out.println(my_date_time);//2020-02-29T12:01:45.949632100
DateTimeFormatter my_format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String my_out_date = my_date_time.format(my_format);
System.out.println("With Formatting: " + my_out_date);//With Formatting: 29-02-2020 11:13:23
//With Formatting: 29-02-2020 12:01:45
}
}
Ouput is here again.
2020-02-29T12:01:45.949632100
With Formatting: 29-02-2020 12:01:45
Using Calendar
package my_proj;
import java.util.Calendar;
public class my_first {
public static void main(String[] args) {
Calendar my_cal = Calendar.getInstance();// created calendar
System.out.println("Today's date is :" + my_cal.getTime());
// create date object using year,month and day
my_cal.set(2020, 0, 25);
// print the result
System.out.println("New Date & time is :" + my_cal.getTime());
}
}
Output is here
Today's date is :Sat Feb 29 15:00:21 IST 2020
New Date & time is :Sat Jan 25 15:00:21 IST 2020
We have created date object by using Year, month and date. Note that January month is considered by using 0. Similarly Feb is 1 , March is 2 ...
Methods
« Java Tutorials