Dates

     

In this topic, I will just present a few classes that do a lot of different things with dates. You can see what kinds of classes, methods, and fields are available to you, and hopefully you can just copy and paste methods here with little modification into your own projects.

Dates.java

 

 package net.dates; import java.util.*; import java.text.*; /** This class contains a number of useful methods that make it convenient to do common operations involving dates. It uses java.util.Calendar and java.util.GregorianCalendar to do so. <p> Hopefully you can paste this directly into your own utilities library. <p> Just modify the classes to accept calendar objects and return the int values. I didn't do this here so that it would make the code easier to read. <p> See the Java API documentation for Calendar and GregorianCalendar for many examples of usage. */ public class Dates { Calendar calendar = Calendar.getInstance(); public static void main(String...ar) {     numberOfDaysInMonth();     dayOfWeek();     getDateDifference(); } //find out the number of days in a month of a given year public static void numberOfDaysInMonth() { //make calendar of the month //you could pass this in as a parameter     Calendar c = new GregorianCalendar(2004,                  Calendar.JULY, 1);     //get number of days in this month     int days = c.getActualMaximum(Calendar.DAY_OF_MONTH); log(days); //31     //month in a leap year     c = new GregorianCalendar(2004,                  Calendar.FEBRUARY, 1);     days = c.getActualMaximum(Calendar.DAY_OF_MONTH); log(days);// 29 } //gets the number of years difference from //some past date and now public static void getDateDifference() {     Calendar now = Calendar.getInstance(); //the date we want to compare to now: Shakespeare is born     Calendar compareDate = new GregorianCalendar(1564, Calendar.APRIL, 23);     //get difference based on year     int yearDifference = now.get(Calendar.YEAR) - compareDate.get(Calendar.YEAR); log(yearDifference);//440 years ago } //The day-of-week is an integer: //1 (Sunday), through 7 (Saturday) public static void dayOfWeek() {     Calendar anv = new GregorianCalendar(2004,                    Calendar.MARCH, 27);     int dayOfWeek = anv.get(Calendar.DAY_OF_WEEK); // 7 log (dayOfWeek); } public String getDate() {         return getMonthInt() + "/" + getDayOfMonth() +                 "/" + getYear();     } /**      * Useful for returning dates in a style      * presentable to end users.      * Returns date in this format:      * Thursday, October 10, 2002      * </p>      */     public String getLongStyleDate() {         String myDate =                getDay() + ", " + getMonth() + " "                + getDayOfMonth() + ", " + getYear();         return myDate;     }     public String getSlashDate() {         String myDate = getMonthInt() + "/"                + getDayOfMonth() + "/" + getYear();         return myDate;     }         ///returns the year     public int getYear() {         return calendar.get(Calendar.YEAR);     }         ///gets the month as a String public String getMonth() {         int mo = getMonthInt();         String[] months = { "January",                  "February", "March",                  "April", "May", "June",                  "July", "August", "September",                  "October", "November", "December" };         if (mo > 12)             return "?";         return months[mo - 1];     }         //gets month as int on scale of 1 - 12         //it is 0 - 11 by default public int getMonthInt() {     return calendar.get(Calendar.MONTH) + 1;     } public int getDayOfMonth() {         return calendar.get(Calendar.DAY_OF_MONTH);     }         //gets the day of week as a string public String getDay() {           int d = getDayOfWeek();           String[] days = {"Sunday", "Monday",                    "Tuesday", "Wednesday",                    "Thursday", "Friday", "Saturday"};           if (d > 7)               return "error";   return days[d - 1]; } public int getDayOfWeek() {       return calendar.get(Calendar.DAY_OF_WEEK); } public int getEra() {       return calendar.get(Calendar.ERA); } public String getUSTimeZone() {       String[] zones = {"Hawaii", "Alaskan", "Pacific",                     "Arizona", "Mountain", "Central",                     "Eastern"};       return zones[10 + getZoneOffset()];    } public int getZoneOffset() {        return calendar.get(Calendar.ZONE_OFFSET)/                              (60*60*1000); } public int getDSTOffset() {       return calendar.get                 (Calendar.DST_OFFSET)/(60*60*1000); } public int getAMPM() {       return calendar.get(Calendar.AM_PM); } public String getTime() {       return getHour() + ":" + getMinute() + ":" +              getSecond(); } public int getHour() {       return calendar.get(Calendar.HOUR_OF_DAY); } public int getMinute() {       return calendar.get(Calendar.MINUTE); } public int getSecond() {       return calendar.get(Calendar.SECOND); } public static String getDateAsString(Date dt) {       return getDateAsString(dt, DateFormat.SHORT); } public static String getDateAsString(Date dt, int                       format) {       if( dt == null )           return "";       return DateFormat.getDateInstance(format)                      .format(dt); } public String getDateTime() {       return getDate() + " " + getTime(); } public static java.util.Date getDate(String str)                                 throws ParseException {       return       DateFormat.getDateInstance(DateFormat.SHORT).                  parse(str); }      /**       * <p>Useful for getting the date in a format       * useable by JDBC.       * Returns current date in this format:       * 2004-03-21 for March 21st, 2004       * </p>       */ public static java.sql.Date getCurrentJDBCDate(){       java.sql.Date date = new java.sql.Date(                   (new java.util.Date()).getTime());       return date;   } public static java.sql.Date getJDBCDate(java.util.Date dt) {       if( dt == null ) {           return null;       }       return new java.sql.Date(dt.getTime()); }       //will print out anything we pass it       //just a convenience to save typing private static <T> void log(T msg) {       System.out.println(msg); } } 

Notice that the preceding class has a number of methods that make it convenient to use dates in various situations: to print to the screen in a user -friendly way, to pass to an SQL database (most of these methods store dates in a manner different than Java does), and for representing dates in different formats appropriate for different occasions.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

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