How to increment decrement date by days in Java - Tutorial example

While working in Java projects, we often needs to increment or decrement date e.g. adding one days to current date to get tomorrow's date, subtracting one day to get yesterday's date etc. Since date in Java is maintained as long millisecond value, Sometime, programmer tend to add 24 hours as one day, which could be wrong if day falls on a day light saving time zone, where a day could be either 23 or 25 hour long. When you add or subtract days from date, other components' of date e.g. month and year must roll. In this Java date tutorial, we will see two ways to increment and decrement date in Java. One approach uses java.util.Calendar from JDK and other uses DateUtils class from Apache commons lang library. DateUtils class provides convenient addDays(Date, int days) method, which accept a date and number of days to add, you can subtract days by passing negative value. Similarly java.util.Calendar provides Calendar.add() method, which accept a calendar field, for adding days, you need to use Calendar.DAY_OF_MONTH. Similar to DateUtils, you can pass positive number to increment date, and negative integer to decrement date in Java.
Read more »

0 Response to "How to increment decrement date by days in Java - Tutorial example"

Posting Komentar