Shubhanshu Sharma
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Java Calendar Class ## Overview Java's calendar class is an abstract class that gives you access to numerous calendar instances and methods for manipulating dates and times. To address several issues with java. util.Date class, the java.util.Calendar class was added to Java with JDK 1.4. It did simplify some tasks; for example, it is now simpler to create arbitrary dates with the new GregorianCalendar(2016, Calendar.JUNE, 11) constructor than with the Date class, where the year starts from 1900 and the month starts from zero. ## Introduction to Java Calendar Class The Java Calendar class is an abstract class that offers methods for converting dates between a specific point in time and a collection of calendar fields like MONTH, YEAR, HOUR, and so on. It derives from an Object and implements a Comparable interface. Because it is an Abstract class, we cannot create an instance with a constructor. To instantiate and implement a sub-class, we must utilize the static method Calendar.getInstance(). ## Declaration ```java= public abstract class Calendar extends Object implements Serializable, Cloneable, Comparable<Calendar> ``` ## Fields for Java Calendar Class The fields for the java.util.Calendar class are listed below. | Fields| Details | | -------- | -------- | | static int ALL_STYLES | This specifies names in all styles, including "January" and "Jan," for getDisplayNames.| | static int AM | The AM PM field value represents the time of day between midnight and shortly before noon. | | static int AM_PM | This is the get and set field number that indicates if the HOUR is before or after noon. | | static int APRIL |In the Gregorian and Julian calendars, this is the value of the MONTH field, indicating the fourth month of the year. | | protected boolean areFieldsSet |This is true if the fields[] match the time currently specified. | | static int AUGUST | In the Gregorian and Julian calendars, this is the value of the MONTH field, representing the eighth month of the year. | | static int DATE | This is the get and set field number that indicates the month's day. | | static int DAY_OF_MONTH |This is the get and set field number that indicates the day of the month. | | static int DAY_OF_WEEK |This is the get and set field number that indicates the weekday.| | static int DAY_OF_WEEK_IN_MONTH | This is the get and set field number that represents the ordinal number of the current month's day of the week. | | static int DAY_OF_YEAR | This is the get and set field number that indicates the current year's day number. | | static int DECEMBER | In the Gregorian and Julian calendars, this is the value of the MONTH field, signifying the twelfth month of the year. | | static int DST_OFFSET |This is the get and set field number that shows the milliseconds of daylight savings time. | | static int ERA | This is the get and set field number that denotes the Julian calendar era, such as AD or BC. | | static int FEBRUARY |In the Gregorian and Julian calendars, this is the value of the MONTH field, indicating the second month of the year. | | static int FIELD_COUNT |This is the number of unique fields that get and set recognise. | | protected int[] fields | This is the calendar field values for the current time on the calendar. | | static int FRIDAY | This is the value of the DAY OF WEEK field for Friday. | | static int HOUR | This is the get and set field number for the hour of the morning or afternoon. | | static int HOUR_OF_DAY | This is the get and set field number that represents the time of day. | | protected boolean[] isSet | These are the flags that indicate whether or not a certain calendar field is set for the calendar.| | protected boolean isTimeSet |If the time value is right, this is true. |static int JANUARY |In the Gregorian and Julian calendars, this is the value of the MONTH field, signifying the first month of the year.| |static int JULY |In the Gregorian and Julian calendars, this is the value of the MONTH field, representing the seventh month of the year. |static int JUNE|In the Gregorian and Julian calendars, this is the value of the MONTH field, indicating the sixth month of the year.| |static int LONG|When a long name, such as "January," is supplied, this is the style specifier for getDisplayName and getDisplayNames.| |static int MARCH|In the Gregorian and Julian calendars, this is the value of the MONTH field, indicating the third month of the year.| |static int MAY|In the Gregorian and Julian calendars, this is the value of the MONTH field, indicating the fifth month of the year.| |static int MILLISECOND|This is the get and set field number, which represents a millisecond inside a second.| |static int MINUTE |This is the get and set field number that indicates the minute inside an hour.| |static int MONDAY |This is the value of the DAY OF WEEK field for Monday.| |static int MONTH |This is the field number for the month for get and set.| |static int NOVEMBER|In the Gregorian and Julian calendars, this is the value of the MONTH field, representing the eleventh month of the year. |static int OCTOBER |In the Gregorian and Julian calendars, this is the MONTH field value for the tenth month of the year. |static int PM |The AM PM field value represents the time of day between noon and shortly before midnight.| |static int SATURDAY|This is the Saturday value for the DAY OF WEEK field. |static int SECOND |This is the get and set field number for the second inside the minute.| |static int SEPTEMBER |In the Gregorian and Julian calendars, this is the value of the MONTH field, representing the ninth month of the year.| |static int SHORT |When a short name, such as "Jan," is supplied, this is the style specifier for getDisplayName and getDisplayNames.| |static int SUNDAY|This is the value of the DAY OF WEEK field for Sunday.| |static int THURSDAY |This is the Thursday value for the DAY OF WEEK field.| |protected long time |After January 1, 1970, 0:00:00 GMT, this is the calendar's current time, reported in milliseconds.| |static int TUESDAY |This is the value of the DAY OF WEEK field for Tuesday.| |static int UNDECIMBER| This is the value for the MONTH field for the thirteenth month of the year..| static int WEDNESDAY| This is the value of the DAY OF WEEK field for Wednesday.| static int WEEK_OF_MONTH | This is the get and set field number that indicates the current month's week number.| static int WEEK_OF_YEAR −|This is the Field number for get and set, which returns the week number for the current year.| static int YEAR |This is the get and set field number that reflects the year.| |static int ZONE_OFFSET |This is the field number used to retrieve and set the raw offset from GMT in milliseconds.## Constructors of Java Calendar Class |Constructor|Descrption| |-----------|-----------| |protected Calendar()|This  constructor creates a Calendar with the default time zone and locale.| |protected Calendar(TimeZone zone, Locale aLocale)|This constructor constructs a calendar with the specified time zone and locale.| ## Methods of Java Calendar Class |Method|Description| |------|------------| |abstract void add(int field, int amount)|Based on the calendar's rules, this function adds or subtracts the provided amount of time from the supplied calendar field.| boolean after(Object when)|This method returns whether this Calendar represents a time after the time represented by the specified Object.|boolean before(Object when)|This function returns if this Calendar reflects a time before the supplied Object's time.| void clear()|This method renders this Calendar's calendar field values and time value (millisecond offset from the Epoch) undefined.|void clear(int field)|This method makes the specified calendar field value and this Calendar's time value (millisecond offset from the Epoch) unknown.| Object clone()|This function copies this object and returns it.| int compareTo(Calendar anotherCalendar)|This function compares two Calendar objects' time values (millisecond offsets from the Epoch).| protected void complete()|This function populates any calendar fields that have unset values.| protected abstract void computeFields()|The current millisecond time value time is converted to calendar field values in fields[].| protected abstract void computeTime()|The current calendar field values in fields[] are converted to the millisecond time value time using this procedure.| boolean equals(Object obj)|This function compares this Calendar to the Object given.| int get(int field)|This function returns the value of the calendar field specified.| int getActualMaximum(int field)|Given the time value of this Calendar, this function returns the greatest value that the specified calendar field might have.| int getActualMinimum(int field)|Given the time value of this Calendar, this function returns the smallest value that the specified calendar field might have.| static Locale[] getAvailableLocales()|This method produces an array containing all locales for which this class's getInstance methods may provide localised instances.| String getDisplayName(int field, int style, Locale locale)| The method returns a string representation of the calendar field value in the style and location specified.| Map<String,Integer> getDisplayNames(int field, int style, Locale locale)|This function produces a Map containing all calendar field names in the provided style and location, as well as their associated field values. |int getFirstDayOfWeek()|This approach determines the first day of the week, such as SUNDAY in the United States and MONDAY in France.| abstract int getGreatestMinimum(int field)|This function returns the Calendar instance's maximum minimum value for the provided calendar field.| static Calendar getInstance()|This function retrieves a calendar based on the current time zone and location.| static Calendar getInstance(Locale aLocale)|This function retrieves a calendar using the default time zone and locale.| static Calendar getInstance(TimeZone zone)|This function retrieves a calendar based on the time zone and locale given.| static Calendar getInstance(TimeZone zone, Locale aLocale|This function returns a calendar with the time zone and locale supplied.| abstract int getLeastMaximum(int field)|This method returns the Calendar instance's lowest maximum value for the provided calendar field.| abstract int getMaximum(int field)|This method returns the maximum value for the provided Calendar instance's calendar property.| int getMinimalDaysInFirstWeek()|This function returns the minimum number of days necessary in the first week of the year; for example, if the first week is defined as one that includes the first day of the first month of the year, this method returns 1.| abstract int getMinimum(int field)|This method returns the smallest value for the provided Calendar instance's calendar property. |Date getTime()|This function returns a Date object with the time value of this Calendar (millisecond offset from the Epoch").| long getTimeInMillis()|This function returns the time value of this Calendar in milliseconds.| TimeZone getTimeZone()|The time zone is obtained using this way.| int hashCode()|This technique This calendar's hash code is returned.| |protected int internalGet(int field)|This function returns the value of the calendar field specified.| boolean isLenient()|This technique indicates if date/time interpretation should be lax.| boolean isSet(int field)|This method detects if a value has been set for the supplied calendar field, including circumstances where the value has been set by internal field computations triggered by a get method call.| abstract void roll(int field, boolean up)|This method adds or subtracts (up/down) a single unit of time from the provided time field while leaving the bigger fields alone.| void roll(int field, int amount)|This method inserts the provided (signed) amount to the chosen calendar field while leaving the bigger fields alone.| void set(int field, int value)|This method changes the value of the specified calendar field.| void set(int year, int month, int date)|This method configures the calendar fields YEAR, MONTH, and DAY OF MONTH.| |void set(int year, int month, int date, int hourOfDay, int minute)|This method populates the calendar fields YEAR, MONTH, DAY OF MONTH, HOUR OF DAY, and MINUTE with values.| void set(int year, int month, int date, int hourOfDay, int minute, int second)|This method populates the fields YEAR, MONTH, DAY OF MONTH, HOUR, MINUTE, and SECOND with values.| |void setFirstDayOfWeek(int value)|This method determines the first day of the week, such as SUNDAY in the United States and MONDAY in France.| void setLenient(boolean lenient)|This method indicates whether date/time interpretation should be lax or strict. |void setMinimalDaysInFirstWeek(int value)|This method specifies the minimum number of days necessary in the first week of the year; for example, if the first week is defined as one that includes the first day of the first month of the year, call this method with value.| void setTime(Date date)|This function sets the time on this Calendar to the supplied Date.| void setTimeInMillis(long millis)|This method sets the current time of this Calendar to the specified long value.| void setTimeZone(TimeZone value)|This method sets the time zone to the specified value.| String toString()|This function returns the calendar's string representation. ## Java Calendar Class Examples ### Example1 In this example we are going to see how to get instance of calendar class and get current date and time. ```java= import java.util.*; public class calendar_demo{ public static void main(String[] args) { // getinstance of calendar class Calendar calendar = Calendar.getInstance(); // getTime() to get the current date and time System.out.print("present Date And Time Is: " + calendar.getTime()); } } ``` **Output** ```java= present Date And Time Is: Wed Oct 26 16:43:14 IST 2022 ``` **Code Explanation** In above example we have used `getInstance()` method to get the Instance of calendar class. `getTime()` is used to get the current date and time. ### Example2 In this example we are going to create instance of calendar class and use `add()` method. ```java= import java.util.Calendar; public class Calendar_demo { public static void main(String[] args) { // getinstance of calendar class Calendar calendar = Calendar.getInstance(); // getTime() to get the current time System.out.println("The current date is : " + calendar.getTime()); // Subtract 15 days from current date calendar.add(Calendar.DATE, -15); System.out.println("15 days ago: " + calendar.getTime()); calendar.add(Calendar.MONTH, 4); // Add 4 month to current calendar System.out.println("4 months later: " + calendar.getTime()); // Add 2 year to current calendar calendar.add(Calendar.YEAR, 2); System.out.println("2 years later: " + calendar.getTime()); } } ``` **Output** ```java= The current date is : Wed Oct 26 16:33:05 IST 2022 15 days ago: Tue Oct 11 16:33:05 IST 2022 4 months later: Sat Feb 11 16:33:05 IST 2023 2 years later: Tue Feb 11 16:33:05 IST 2025 ``` **Code Explanation** In Above example we have created a instance of calendar class using `getinstance()` method. We have used `add()` method to with field parameter as `Calender.DATE` and amount parameter as -15 this will allow us to get 15 days before current time. ### Example 3 In this example we are going to use `getMaximum()` method. ```java= import java.util.*; public class calendar_demo { public static void main(String[] args) { // get instance of calendar class Calendar calendar = Calendar.getInstance(); // get maximum number of day in week int maximum = calendar.getMaximum(Calendar.DAY_OF_WEEK); System.out.println("Maximum number of days in week: " + maximum); // get maximum week in year maximum = calendar.getMaximum(Calendar.WEEK_OF_YEAR); System.out.println("Maximum number of weeks in year: " + maximum); } } ``` **Output** ```java= Maximum number of days in week: 7 Maximum number of weeks in year: 53 ``` **Code Explanation** In this example we have used `getMaximum()` to get the maximum value of days in week and weeks in year. ## Conclusion * The Java Calendar class is an abstract class that offers methods for converting dates between a certain point in time and a collection of calendar fields like MONTH, YEAR, HOUR, and so on. * Because it is an Abstract class, we cannot create an instance with a constructor * To instantiate and implement a sub-class, we must instead utilise the static method Calendar.getInstance() * `add()` function adds or subtracts the provided amount of time from the supplied calendar field. * `getTime()` returns a Date object with the time value of this Calendar (millisecond offset from the Epoch")

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully