tuntun fdg
tuntun fdg

Reputation: 511

Regarding adding days to the current date

I am a newbie to the world of java. I am learning and exploring the java calendar class which is an abstract class consisting of a factory method get instance (). I was trying to increment or decrement the date, e.g. adding one day to the current date to get tomorrow's date, subtracting one day to get yesterday's date, etc. Since date in Java is maintained as a long millisecond value, sometimes programmers tend to add 24 hours as one day. This could be wrong if the day falls on a daylight saving timezone, where a day could be either 23 or 25 hours long. When you add or subtract days from date, other components of date e.g. month and year must roll.

My query is as shown below. In the class I was trying to add and subtract the days. Please advise, is it the correct approach or is there any other better approach that you would advise.

    //Using Calendar to increment and decrement days from date in Java
     Date today = new Date(); 
    System.out.println("Today is " + toddMMyy(today)); 
    Calendar cal = Calendar.getInstance(); //adding one day to current date cal.add(Calendar.DAY_OF_MONTH, 1); 
    Date tommrrow = cal.getTime(); 
    System.out.println("Tomorrow will be " + toddMMyy(tommrrow)); //substracting two day from date in Java
    cal.add(Calendar.DAY_OF_MONTH, -2); 
Date yesterday = cal.getTime(); System.out.println("Yesterday was " + MMyy(cal.getTime()));

Upvotes: 2

Views: 297

Answers (1)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

Your are correct. This is what happens when we use Date milliseconds arithmetic

     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
     Date d1 = df.parse("2013-03-30 12:00");
     Date d2 = new Date(d1.getTime() + 24 * 3600 * 1000);  // +24 hrs
     System.out.println(df.format(d2));

output

2013-03-31 13:00

Upvotes: 1

Related Questions