How to add 24 hrs to date in Java?In order to add 24 hours (1 day) to a date in Java, we can use the 'Calendar' class and its add() method. Here's an example: Filename: Twentyfourhours.java Output: Tue Jan 10 14:58:36 UTC 2023 Filename: Twentyfourhours.java Output: Tue Jan 10 15:45:56 UTC 2023 It will print the date that is one day after the current date. If you want to add a different number of hours, we can use the 'Calendar.HOUR' field instead of 'Calendar.DATE'. For example, to add 48 hours (2 days), we can use 'calendar.add(Calendar.HOUR, 48)'. Alternatively, we can use the 'java.time' package, which is part of Java 8 and later. The 'java.time' package provides a more modern and easier-to-use API for date and time operations. Here's an example of how to add 1 day to a 'LocalDate' object using the 'java.time' package: Filename: Twentyfourhours.java Output: 2023-01-10 To add 24 hours to a date in Java, you can use the 'add()' method of the 'Calendar' class. Here's an example of how we can do this: Filename: Twentyfourhours.java Output: Tue Jan 10 15:07:57 UTC 2023 Alternatively, we can use the 'java.time' package introduced in Java 8 to add 24 hours to a date. Here's an example of how you can do it: Filename: Twentyfourhours.java Output: 2023-01-10T15:42:10.425 Alternatively, we can also use the 'java.time' package introduced in Java 8 to add 24 hours to a 'java.time.LocalDateTime' or 'java.time.ZonedDateTime' object. Here's an example of how to do it using 'LocalDateTime': Filename: Twentyfourhours.java Output: 2023-01-10T15:50:23.686 It will add 24 hours to the current date and time stored in the 'LocalDateTime' object and print the resulting date and time to the console. we can also use the 'java.util.Date' class to perform arithmetic on dates. Here's an example of how you can do it: Filename: Twentyfourhours.java Output: Tue Jan 10 15:54:19 UTC 2023 In order to add 24 hours to a date in Java, we can use the Calendar class and the add() method. Here is an example: Filename: Twentyfourhours.java Output: Tue Jan 10 15:57:17 UTC 2023 It will add 24 hours to the current date and time. If we want to add 24 hours to a specific date, we can use the setTime() method to set the date on the Calendar instance before adding the hours. For example: Filename: Twentyfourhours.java Output: Wed May 13 07:06:40 UTC 2020 Keep in mind that the Calendar class uses a zero-based numbering system for the months (i.e. January is 0, February is 1, etc.), so you may need to adjust the month and day values accordingly. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India