Recipe 6.10 Day of WeekMonthYear or Week Number


Recipe 6.10 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. Note that months start at zero (for indexing an array of Strings), while the other values start at 1:

Year: 2005 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



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net