Skip to content

Tag: java.util.Calendar

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