Algorithm
-
Import Necessary Packages:
- Import the required packages to access date and time-related classes.
-
Create a Date Object:
- Create an object of the
java.util.Date
class to represent the current date and time.
- Create an object of the
-
Create a Calendar Object:
- Create an object of the
java.util.Calendar
class and set its time to the current date and time.
- Create an object of the
-
Get Current Date and Time:
- Use the
getTime()
method of theDate
object to get the current date and time. - Use the
get
methods of theCalendar
object to extract individual components like year, month, day, hour, minute, and second.
- Use the
-
Print or Use the Current Date/Time:
- Print or use the extracted date and time components as needed in your program.
Code Examples
#1 Code Example- Get Current date and time in default format
Code -
Java Programming
import java.time.LocalDateTime;
public class CurrentDateTime {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
System.out.println("Current Date and Time is: " + current);
}
}
Copy The Code &
Try With Live Editor
Output
#2 Code Example- Get Current date and time with pattern
Code -
Java Programming
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentDateTime {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String formatted = current.format(formatter);
System.out.println("Current Date and Time is: " + formatted);
}
}
Copy The Code &
Try With Live Editor
Output
#3 Code Example- Get Current Date time using predefined constants
Code -
Java Programming
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentDateTime {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
String formatted = current.format(formatter);
System.out.println("Current Date is: " + formatted);
}
}
Copy The Code &
Try With Live Editor
Output
#4 Code Example- Get Current Date time in localized style
Code -
Java Programming
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
public class CurrentDateTime {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
String formatted = current.format(formatter);
System.out.println("Current Date is: " + formatted);
}
}
Copy The Code &
Try With Live Editor
Output
Demonstration
Java Programing Example to Get Current Date/TIme-DevsEnv