Get Current Date and Time in JavaThere are many ways to get current date and time in java. There are many classes that can be used to get current date and time in java.
Get Current Date and Time: java.time.format.DateTimeFormatterThe LocalDateTime.now() method returns the instance of LocalDateTime class. If we print the instance of LocalDateTime class, it prints current date and time. To format the current date, you can use DateTimeFormatter class which is included in JDK 1.8. Test it NowOutput: 2017/11/06 12:11:58 Get Current Date and Time: java.text.SimpleDateFormatThe SimpleDateFormat class is also used for formatting date and time. But it is old approach. Test it NowOutput: 06/11/2017 12:26:18 Get Current Date: java.time.LocalDateThe LocalDate.now() method returns the instance of LocalDate class. If we print the instance of LocalDate class, it prints current date. Output: 2017-01-23 Get Current Time: java.time.LocalTimeThe LocalTime.now() method returns the instance of LocalTime class. If we print the instance of LocalTime class, it prints current time. Output: 00:01:14.341 Get Current Date & Time: java.time.LocalDateTimeThe LocalDateTime.now() method returns the instance of LocalDateTime class. If we print the instance of LocalDateTime class, it prints current date and time both. Output: 2017-01-24T00:03:31.593 Get Current Date & Time: java.time.ClockThe Clock.systemUTC().instant() method returns current date and time both. Output: 2017-01-23T18:35:23.669Z Get Current Date & Time: java.util.DateBy printing the instance of java.util.Date class, you can print current date and time in java. There are two ways to do so. 1st way: 2nd way: Output: Thu Mar 26 08:22:02 IST 2015 Get Current Date: java.sql.DateBy printing the instance of java.sql.Date class, you can print current date in java. It doesn't print time. This date instance is generally used to save current date in database. Output: 2015-03-26 Get Current Date & Time: java.util.CalendarCalendar class can be used to get the instance of Date class. The getTime() method of Calendar class returns the instance of java.util.Date. The Calendar.getInstance() method returns the instance of Calendar class. Output: Thu Mar 26 08:22:02 IST 2015 Note: It is recommended to use Calendar class for getting current date and time in classical Date API. Since Java 8, you can use LocalDate, LocalTime or LocalDateTime classes.
Next TopicJava Convert String to int
|