Skip to content

Java Calendar Examples

import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        Calendar today = Calendar.getInstance();
        System.out.println("Today is  " + today.getTime());
    }
}

In this simplest example of Calendar, the output would be

Today is : Tue Jul 01 10:56:14 BRT 2008

In the next example how to get information about the day inside the year, month and week.

import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        Calendar today = Calendar.getInstance();
        int dof = today.get(Calendar.DAY_OF_YEAR);
        int dom = today.get(Calendar.DAY_OF_MONTH);
        int dow = today.get(Calendar.DAY_OF_WEEK);
        System.out.println("Today is the " + dof +"º day in this year,");
        System.out.println("the " + dom +"º day in this month");
        System.out.println("and the " + dow +"º day in this week.");
    }
}

The output could be

Today is the 183º day in this year,
the 1º day in this month
and the 3º day in this week.

The next example is about how to add (and subtract) a duration from a Calendar.

import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        Calendar today = Calendar.getInstance();
        System.out.println("Today is " + today.getTime());

        Calendar yesterday = (Calendar)today.clone();
        yesterday.add(Calendar.DATE, -1);
        System.out.println("Yesterday was " + yesterday.getTime());

        Calendar tomorow = (Calendar)today.clone();
        tomorow.add(Calendar.DATE, 1);
        System.out.println("Tomorow will be " + tomorow.getTime());
    }
}

A typical output would be

Today is Tue Jul 01 10:44:18 BRT 2008
Yesterday was Mon Jun 30 10:44:18 BRT 2008
Tomorow will be Wed Jul 02 10:44:18 BRT 2008

Published inenglish

5 Comments

  1. John John

    hi i am john,
    i am new to andriod ,
    i want to develope calendar application in android
    i dont know how to start,
    can u help me in doing so.
    on selecting the calendar in menu it should display current date with events in time slots

  2. Felipe Alexandre Rodrigues Felipe Alexandre Rodrigues

    How i can set a specific date at var Calendar ?
    Thx, congrats

  3. Migeal Quroni Zotto Migeal Quroni Zotto

    Hi my name is Rudi,
    Im a student that is currently studying android
    and i have a project that i need to develop a calendar application in android …

    plzzzz can you help me
    because i don’t know where to start

Leave a Reply

Your email address will not be published. Required fields are marked *