Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Day of Week/Month/Year or Week Number

Problem

You have a date and need to find what day of the week, month, or year that date falls on.

Solution

Use the Calendar class’s get( ) method, which has constants for retrieving most such values.

Discussion

The Calendar class can return most of these:

// CalendarDemo.java
Calendar c = Calendar.getInstance(  );    // today
System.out.println("Year: " + c.get(Calendar.YEAR));
System.out.println("Month: " + c.get(Calendar.MONTH));
System.out.println("Day: " + c.get(Calendar.DAY_OF_MONTH));
System.out.println("Day of week = " + c.get(Calendar.DAY_OF_WEEK));
System.out.println("Day of year = " + c.get(Calendar.DAY_OF_YEAR));
System.out.println("Week in Year: " + c.get(Calendar.WEEK_OF_YEAR));
System.out.println("Week in Month: " + c.get(Calendar.WEEK_OF_MONTH));
System.out.println("Day of Week in Month: " + 
            c.get(Calendar.DAY_OF_WEEK_IN_MONTH));
System.out.println("Hour: " + c.get(Calendar.HOUR));
System.out.println("AM or PM: " + c.get(Calendar.AM_PM));
System.out.println("Hour (24-hour clock): " + 
            c.get(Calendar.HOUR_OF_DAY));
System.out.println("Minute: " + c.get(Calendar.MINUTE));
System.out.println("Second: " + c.get(Calendar.SECOND));

This chatty program shows most of the fields in the Calendar class:

Year: 1999
Month: 6
Day: 19
Day of week = 2
Day of year = 200
Week in Year: 30
Week in Month: 4
Day of Week in Month: 3
Hour: 3
AM or PM: 1
Hour (24-hour clock): 15
Minute: 18
Second: 42
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata