Manage Dates in Java
This is a class to help you manage Dates in Java. There are different methods to help you create dates from differerent date formats.
This class uses the Calendar class, but makes dates easier to manage.
Day Class
package com.delegata.diamond.common.util;
import com.delegata.diamond.common.util.SortInterface;
import java.io.Serializable;
import java.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Written by Greg Dias
*
* Purpose: This is a Day class which is used
* for date information.
* Month in this class starts at zero and 11 is December.
*/
public class Day
implements Cloneable, Serializable,SortInterface
{
private static final Log log = LogFactory.getLog(Day.class);
protected Calendar calendar_;
static final long serialVersionUID = 0L;
/**
*
* @param year
* @param month
* @param dayOfMonth
*/
private void initialize(int year, int month, int dayOfMonth)
{
calendar_ = Calendar.getInstance();
calendar_.setLenient(true);
calendar_.setFirstDayOfWeek(2);
calendar_.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
set(year, month, dayOfMonth);
}
/**
* This string date should be in this format: 05/14/2008 (month,day,year)
* @param day
*/
public Day(String day,String pass_in_empty_string) throws Exception
{
try
{
int year=new Integer(day.substring(6,10)).intValue();
int day1=new Integer(day.substring(3,5)).intValue();
int month=new Integer(day.substring(0,2)).intValue();
month=month-1;
initialize(year, month,day1);
}
catch(Exception e)
{
log.error((new StringBuilder()).append("Error in setting Date with String").append(e).toString());
throw new Exception("Invalid Date");
}
}
/**
* This string date should be in this format: 2004-04-15 (year, month,day)
* @param day
*/
public Day(String day) throws Exception
{
try
{
int year=new Integer(day.substring(0,4)).intValue();
int month=new Integer(day.substring(4,7)).intValue();
int day1=new Integer(day.substring(8,10)).intValue();
initialize(year, month,day1);
}
catch(Exception e)
{
log.error((new StringBuilder()).append("Error in setting Date with String").append(e).toString());
throw new Exception("Invalid Date");
}
}
/**
*
* @param year
* @param month
* @param dayOfMonth
*/
public Day(int year, int month, int dayOfMonth)
{
initialize(year, month, dayOfMonth);
}
/**
*
* @param year
* @param dayOfYear
*/
public Day(int year, int dayOfYear)
{
initialize(year, 0, 1);
calendar_.set(6, dayOfYear);
}
/**
* Purpose: Will initialize the Day class to the current Day.
*
*/
public Day()
{
Calendar calendar = Calendar.getInstance();
initialize(calendar.get(1), calendar.get(2), calendar.get(5));
calendar.setFirstDayOfWeek(2);
}
/**
*
* @param calendar
*/
public Day(Calendar calendar)
{
this(calendar.get(1), calendar.get(2), calendar.get(5));
}
/**
*
* @param date
*/
public Day(Date date)
{ if(date==null)
date=new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
initialize(calendar.get(1), calendar.get(2), calendar.get(5));
}
/**
*
* @param time
*/
public Day(long time)
{
this(new Date(time));
}
/**
*
* @param day
*/
public Day(Day day)
{
this(day.getYear(), day.getMonth(), day.getDayOfMonth());
}
/**
* Purpose: To clone this class.
*/
public Object clone()
{
return new Day(this);
}
/**
*
*
*/
public static Day today()
{
return new Day();
}
/**
*
* @return Calendar
*/
public Calendar getCalendar()
{
return (Calendar)calendar_.clone();
}
/**
*
* @return Date
*/
public Date getDate()
{
return getCalendar().getTime();
}
/**
*
* @param object
* @return int
*/
public int compareTo(Object object)
{
Day day = (Day)object;
return calendar_.getTime().compareTo(day.calendar_.getTime());
}
/**
* Purpose: Is the Day after this day.
* @param day
* @return boolean
*/
public boolean isAfter(Day day)
{
return calendar_.after(day.calendar_);
}
/**
* Purpose: Is the day before this day.
* @param day
* @return boolean
*/
public boolean isBefore(Day day)
{
return calendar_.before(day.calendar_);
}
/**
* Is day equal to this day.
* @param day
* @return boolean
*/
public boolean equals(Day day)
{
if(this.toString().trim().compareTo(day.toString().trim())==0)
return true;
return false;
}
public int hashCode()
{
return calendar_.hashCode();
}
/**
*
* @param year
* @param month
* @param dayOfMonth
*/
public void set(int year, int month, int dayOfMonth)
{
setYear(year);
setMonth(month);
setDayOfMonth(dayOfMonth);
}
public int getYear()
{
return calendar_.get(1);
}
public void setYear(int year)
{
calendar_.set(1, year);
}
/**
* Purpose: Retrieves what the first day of the week is.
* Default is Sunday which is number 1.
* @return int
*/
public int getFirstDayOfWeek()
{
return calendar_.getFirstDayOfWeek();
}
/**
* Purpose: Sets the first day of the week to be Monday.
*
*/
public void setFirstDayOfWeek()
{
calendar_.setFirstDayOfWeek(2);
}
public int getMonth()
{
return calendar_.get(2);
}
/**
* Purpose: Retrieves the Month Number where 1 would be January.
* @return int
*/
public int getMonthNo()
{
switch(getMonth())
{
case 0: // '\0'
return 1;
case 1: // '\001'
return 2;
case 2: // '\002'
return 3;
case 3: // '\003'
return 4;
case 4: // '\004'
return 5;
case 5: // '\005'
return 6;
case 6: // '\006'
return 7;
case 7: // '\007'
return 8;
case 8: // '\b'
return 9;
case 9: // '\t'
return 10;
case 10: // '\n'
return 11;
case 11: // '\013'
return 12;
}
return 0;
}
/**
* Purpose: Sets this class where January is zero.
* @param month
*/
public void setMonth(int month)
{
calendar_.set(2, month);
}
/**
* Purpose: Retrieves the day of the month where 1 is the
* first day of the month.
* @return int
*/
public int getDayOfMonth()
{
return calendar_.get(5);
}
/**
*
* @param dayOfMonth
*/
public void setDayOfMonth(int dayOfMonth)
{
calendar_.set(5, dayOfMonth);
}
/**
* Purpose: Retrieves the day of the year.
* @return int
*/
public int getDayOfYear()
{
return calendar_.get(6);
}
/**
* Retrieves the day of the week. (either: Sunday, Monday, ... , Saturday)
* @return int
*/
public int getDayOfWeek()
{
return calendar_.get(7);
}
public int getDayNumberOfWeek()
{
return getDayOfWeek() != 1 ? getDayOfWeek() - 1 : 7;
}
public int getWeekOfYear()
{
return calendar_.get(3);
}
/**
* Purpose: Add Days to the Day class.
* @param nDays
*/
public void addDays(int nDays)
{
calendar_.add(5, nDays);
}
/**
* Purpose: Subtract Days to this Day class.
* @param nDays
*/
public void subtractDays(int nDays)
{
addDays(-nDays);
}
/**
* Purpose: Add Months to this day class.
* @param nMonths
*/
public void addMonths(int nMonths)
{
calendar_.add(2, nMonths);
}
/**
* Purpose: Subtract Months to this day class.
* @param nMonths
*/
public void subtractMonths(int nMonths)
{
addMonths(-nMonths);
}
/**
* Purpose: Add years to this day class.
* @param nYears
*/
public void addYears(int nYears)
{
calendar_.add(1, nYears);
}
/**
* Purpose: Subtract Days to this day class.
* @param nYears
*/
public void subtractYears(int nYears)
{
addYears(-nYears);
}
public int getDaysInYear()
{
return calendar_.getActualMaximum(6);
}
/**
* Purpose: Returns if this day year is a leap year or not.
* @return boolean
*/
public boolean isLeapYear()
{
return getDaysInYear() == calendar_.getMaximum(6);
}
/**
* Purpose: Returns if the input year is a leap year.
* @param year
* @return boolean
*/
public static boolean isLeapYear(int year)
{
return (new Day(year, 0, 1)).isLeapYear();
}
public int getDaysInMonth()
{
return calendar_.getActualMaximum(5);
}
public String getDayName()
{
switch(getDayOfWeek())
{
case 2: // '\002'
return "Monday";
case 3: // '\003'
return "Tuesday";
case 4: // '\004'
return "Wednesday";
case 5: // '\005'
return "Thursday";
case 6: // '\006'
return "Friday";
case 7: // '\007'
return "Saturday";
case 1: // '\001'
return "Sunday";
}
return null;
}
public String getMonthName()
{
switch(getMonth())
{
case 0:
return "January";
case 1:
return "February";
case 2:
return "March";
case 3:
return "April";
case 4:
return "May";
case 5:
return "June";
case 6:
return "July";
case 7:
return "August";
case 8:
return "September";
case 9:
return "October";
case 10:
return "November";
case 11:
return "December";
}
return null;
}
public int daysBetween(Day day)
{
long millisBetween = Math.abs(calendar_.getTime().getTime() - day.calendar_.getTime().getTime());
return Math.round(millisBetween / 0x5265c00L);
}
public static Day getNthOfMonth(int n, int dayOfWeek, int month, int year)
throws ArrayIndexOutOfBoundsException
{
if(dayOfWeek < 0 dayOfWeek > 6)
throw new ArrayIndexOutOfBoundsException(dayOfWeek);
Day first = new Day(year, month, 1);
int offset = dayOfWeek - first.getDayOfWeek();
if(offset < 0)
offset = 7 + offset;
int dayNo = (n - 1) * 7 + offset + 1;
return dayNo <= first.getDaysInMonth() ? new Day(year, month, dayNo) : null;
}
public static Day getFirstOfMonth(int dayOfWeek, int month, int year)
{
return getNthOfMonth(1, dayOfWeek, month, year);
}
/**
* Purpose: Sets this Day using a string.
* Format should be 09/12/2006 or 9/12/2006.
* If string is in wrong format, it
* will throw an ApplicationException.
* @param Date
* @throws ApplicationException
*/
public void setDate(String Date) throws Exception
{
int month = 0;
int day = 0;
int year = 0;
String subString = "";
Integer integer = null;
subString = Date.substring(0, 1);
String conv = "";
int length = Date.length();
int x = 0;
try
{
while(x < length && subString.compareTo("/") != 0)
{
conv = (new StringBuilder()).append(conv).append(subString).toString();
x++ ;
subString = Date.substring(x, x + 1);
}
integer = new Integer(conv);
month = integer.intValue();
x++ ;
subString = Date.substring(x, x + 1);
conv = "";
for(; x < length && subString.compareTo("/") != 0; subString = Date.substring(x, x + 1))
{
conv = (new StringBuilder()).append(conv).append(subString).toString();
x++ ;
}
integer = new Integer(conv);
day = integer.intValue();
x++ ;
subString = Date.substring(x, x + 1);
conv = "";
do
{
if(x >= length subString.compareTo("/") == 0)
break;
conv = (new StringBuilder()).append(conv).append(subString).toString();
if( ++ x != length)
subString = Date.substring(x, x + 1);
} while(true);
integer = new Integer(conv);
year = integer.intValue();
}
catch(Exception e)
{
log.error((new StringBuilder()).append("Error in setting Date with String").append(e).toString());
throw new Exception("Invalid Date");
}
set(year, --month, day);
}
public static Day getLastOfMonth(int dayOfWeek, int month, int year)
{
Day day = getNthOfMonth(5, dayOfWeek, month, year);
return day == null ? getNthOfMonth(4, dayOfWeek, month, year) : day;
}
/**
* Purpose: toString method that will return this
* class in the format of 09/12/2006.
*/
public String toString()
{
StringBuffer string = new StringBuffer();
if(getMonth() < 9)
string.append('0');
string.append(getMonth() + 1);
string.append('/');
if(getDayOfMonth() < 10)
string.append('0');
string.append(getDayOfMonth());
string.append('/');
string.append(getYear());
return string.toString();
}
public Day getDay()
{
return this;
}
//Required by sort interface
public int getSortInteger()
{
return 0;
}
}

0 comments:
Post a Comment