The i18n Cookbook - recipies for a global society

  • java cookbook
  • about the author
Home › Java Internationalization Cookbook › Dates and Times › Calendars

Java Cookbook

  • Java Internationalization Cookbook
    • Locales
    • Dates and Times
      • Calendars
        • Gregorian Calendar
        • Hebrew Calendar
        • Japanese Calendar
        • Chinese Calendar
        • Find the Chinese zodiac for a Gregorian year
        • Get the name of the current month
        • Get the first day of the week
        • Add time to Calendar
        • Get an array of Holidays
        • Find the date for the Chinese New Year
        • Get all the Era names for the Japanese Calendar
        • Get the Japanese era for a Gregorian date
      • Formating dates and times
    • Numerical Systems
    • Misc
    • Resource Bundles
    • Unicode, Transliteration, and Charactersets

Add time to Calendar

Problem:

You need to add or subtract time from a calendar.

Solution:

There are two ways to perform date math with a Calendar, use add(int,int) or roll(int,int). Roll will increment or decrement the specified field until the maximum or minimum value is reached, and then it will begin again. Adding 13 months to the calendar with roll will not increment the year.

Add will bubble up such that adding 13 months to a Calendar will also increment the year. To get the current date and add 3 months:

Calendar c = Calendar.getInstance(Locale.GERMAN); System.out.println(c.getTime()); c.add(Calendar.MONTH, 3); System.out.println(c.getTime());

To get the current date and subtract 7 weeks:

Calendar c = Calendar.getInstance(Locale.GERMAN); System.out.println(c.getTime()); c.add(Calendar.WEEK_OF_MONTH, -7); System.out.println(c.getTime());

‹ Get the first day of the week up Get an array of Holidays ›
  • calendar
  • Printer-friendly version
  • Add new comment

If you are testing any of these recipes in Eclipse and the characters are not displaying correctly in your console visit http://i18ncookbook.com/eclipse_settings.

This site is ad supported.  I hope you find something among our sponsors worth clicking. ;)

i18n search

Google
Custom Search

Search

Tags in Tags

calendar date icu4j Java Locale number format numberformat parse spellout timezone transliteration transliterator
more tags

User login

  • Create new account
  • Request new password
  • java cookbook
  • about the author