GET DATE AND TIME IN 4 WAYS USING JAVA
We can display the date and time in 4 different ways by using default java classes
- they are:-
-
- SimpleDateFormat.
- Date.
- LocalDate.
- LocalDataTime.
1.SimpleDateFormat
The SimpleDateFormat is the predefined class in java.
This method was used in before java 8 .when we use this class.import the
" Java.text.SimpleDateFormat;"
"Java.util.calender;"
Package in the project is mandatory. This class will print the current date and the time in our system default.
package date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Sdf {
public static void main(String[] args) {
String date = new SimpleDateFormat("yyyy_mm_dd_hh_mm_ss").format(Calendar.
getInstance().getTime()); System.out.println(date);
}
}
OUTPUT:
2.Date (Traditional Date class)
The Date is the predifined class in java.This method also was used in before java 8 .when we use this class.import
"import java.time.LocalDate;"
Package in the project is mandatory. This Class method will print the date and time with the name of the date and the month.
package date;
import java.time.LocalDate;
import java.util.Date;
public class Sdf {
public static void main(String[] args) {
Date date=new Date(System.currentTimeMillis());
System.out.println(date);
}
}
OUTPUT:
3.LocalDate
The LocalDate is the predifined class in java .Then this methods was used after the version 8 in java.when we use this class.import the
"import java.time.LocalDate;"
Package in the project is mandatory.This class was print only the date.
package date;
import java.time.LocalDate;
public class Sdf {
public static void main(String[] args) {
LocalDate ld=LocalDate.now();
System.out.println(ld);
}
}
OUTPUT:
4.LocalDateTime
The LocalDateTime is the predifined class in java .when we use this class,import the
" Java.time.LocalDateTime;"
public static void main(String[] args) {
LocalDateTime ld=LocalDateTime.now();
System.out.println(ld);
}
}
Superb akash
ReplyDeleteThank for your response.🤝.
Delete