how to validate date formate YYYY-MM-DDThh:mm:ss ?

i have implemented validation for YYYY-MM-DD

but how to validate for time

here is the code for date validation

could you please anyone help me on this issue

public static boolean validateDateFormate(String date)

{

try {

String dateFormat="yyyy-MM-ddYYYY-MM-DDThh:mm:ss";

String temp = date.substring(0,date.indexOf("-"));

if(temp.length()!= 4)

return false;

SimpleDateFormat df=new SimpleDateFormat(dateFormat);

Date date1=df.parse(date);

String resultDateString=df.format(date1);

System.out.println("date1"+resultDateString);

if ( !date.equals(resultDateString)) { return false; }

} catch (Exception de) {

System.out.println(de);

return false;

}

return true;

}

[803 byte] By [sreenussunaccounta] at [2007-11-27 11:11:52]
# 1

But what exactly is the problem?

prometheuzza at 2007-7-29 13:50:56 > top of Java-index,Java Essentials,Java Programming...
# 2

i want validation for this format YYYY-MM-DDThh:mm:ss

that code validate only YYYY-MM-DD this format

if i pass YYYY-MM-DDThh:mm:ss this to SimpleDateFormat

giving error

how to validate YYYY-MM-DDThh:mm:ss this format can u help me on this

thanks for replying soon

sreenussunaccounta at 2007-7-29 13:50:56 > top of Java-index,Java Essentials,Java Programming...
# 3

... and use the code formatting code when posting programs. Unformatted code sends my eyes funny :S

c0demonk3ya at 2007-7-29 13:50:56 > top of Java-index,Java Essentials,Java Programming...
# 4

A useful Data util class

import java.text.DateFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.StringTokenizer;

public final class SlacDate implements Comparable

{

public final static int FormatDDMMCCYY= 0;

public final static int FormatMMDDCCYY= 1;

public final static int FormatDATETIME= 2;

public final static int FormatMMMDDTIME= 3;

public final static int FormatTIMESTAMP= 4;

public final static int FormatCCYYMMDD= 5;

public final static int FormatCCYYMMDDHHMM= 6;

public final static int FormatCCYYMMDDHHMMSS= 7;

public final static int FormatDDMMCCYYTIME= 8;

public final static int FormatDATEVERBOSE= 9;

public final static int FormatDATETIMEVERBOSE= 10;

public final static int FormatHHMMSS= 11;

public final static int FormatHHMMSSMIL= 12;

public final static int FormatDB2TIMESTAMP= 13;

public final static int FormatUDBTIMESTAMP= 14;

public final static int JANUARY= 1;

public final static int FEBRUARY= 2;

public final static int MARCH= 3;

public final static int APRIL= 4;

public final static int MAY= 5;

public final static int JUNE= 6;

public final static int JULY= 7;

public final static int AUGUST= 8;

public final static int SEPTEMBER= 9;

public final static int OCTOBER= 10;

public final static int NOVEMBER= 11;

public final static int DECEMBER= 12;

public final static int MONTHS_IN_YEAR = 12;

public final static int SUNDAY= 1;

public final static int MONDAY= 2;

public final static int TUESDAY= 3;

public final static int WEDNESDAY= 4;

public final static int THURSDAY= 5;

public final static int FRIDAY= 6;

public final static int SATURDAY= 7;

public final static int DAYS_IN_WEEK = 7;

private final static int DefaultHours= 12;

private final static int DefaultMinutes = 0;

private final static int DefaultSeconds = 0;

private final static int DefaultMillis= 0;

private final static int DaysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

private final static String MonthAbbrev[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

private final static String MonthVerbose[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

private final static String DaysOfWeekAbbrev[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

private final static String DaysOfWeek[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

private final static String DayExtension[] = { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };

private final static String EMPTY = "";

private final static String COLON = ":";

private final static String PERIOD = ".";

private final static String HYPHEN = "-";

private final static String SPACE = " ";

private final static String ZERO = "0";

private static String s_dateSep = HYPHEN;

private int m_dd, m_mm, m_yyyy, m_hh, m_min, m_ss, m_mil;

private static long MillisInSecond= 1000;

private static long MillisInMinute= MillisInSecond * 60;

private static long MillisInHour= MillisInMinute * 60;

private static long MillisInDay= MillisInHour * 24;

/**

* JDK_BST_FIX

* Static initialisation block - check JDK vendor/version in order to determine whether

* an adjustment to correctly report British summertime needs to be made. This is required

* in order to fix a bug in some Sun & IBM JDKs. If an untested version of the Sun or IBM JDK

* is used, we log an error message warning that this block of code should be examained and

* changed as appropriate. This is ugly, but will prevent a new JDK being used and this bug

* creeping back in.

*

* Note the following JDKs have been tested under both NT & AIX

*JDK Version NTAIX

*1.1.7 (IBM)xx

*1.1.7A (IBM)?

*1.1.7B (IBM)?

*1.1.8 (IBM)xx

*1.2.2 (IBM)okok

*1.1.7 (SUN)xx

*1.1.8 (SUN)xx

*1.2 (SUN)xx

*/

private final static String SunVendorString = "Sun Microsystems Inc.";

private final static String IBMVendorString = "IBM"; // Can also be 'IBM Corporation'

private final static String SunProblemJDKs[] = { "1.1.4", "1.1.5", "1.1.6", "1.1.7", "1.1.7A", "1.1.7B", "1.1.8", "1.2", "1.2.2" };

private final static StringSunOKJDKs[] = { "1.0.2", "1.1.2", "1.1.3", "1.4.0", "1.4.2"};

private final static String IBMProblemJDKs[] = { "1.1.4", "1.1.5", "1.1.6", "1.1.7", "1.1.7A", "1.1.8" };

private final static StringIBMOKJDKs[] = { "1.0.2", "1.1.2", "1.1.3", "1.1.7B", "1.2.2", "1.3.0", "1.3.1" };

private static boolean s_adjustForBST = false;

static

{

String vendor = System.getProperty("java.vendor");

String jdk = System.getProperty("java.version");

// Check applies to Sun only.

if (vendor.equals(SunVendorString) || vendor.startsWith(IBMVendorString))

{

String problemJDKs[] = null;

String OKJDKs[] = null;

if (vendor.equals(SunVendorString))

{

problemJDKs = SunProblemJDKs;

OKJDKs = SunOKJDKs;

}

else

{

problemJDKs = IBMProblemJDKs;

OKJDKs = IBMOKJDKs;

}

// Determine whether we need to make adjustment

for (int i = 0; i < problemJDKs.length; i++)

{

if (problemJDKs[i].equals(jdk))

{

s_adjustForBST = true;

break;

}

}

// If we do not need to make the adjustment then check that the

// JDK reported is one of the versions that we know to be good.

// If it is not log an error message.

if (!s_adjustForBST)

{

boolean goodJDK = false;

for (int i = 0; i < OKJDKs.length; i++)

{

if (OKJDKs[i].equals(jdk))

{

goodJDK = true;

break;

}

}

/* CR176 - we now anticipate that all JDKs post 1.3.x are "good" ones

if (!goodJDK)

{

// We do not use the SingletonLogger mechanism since we

// cannot be sure that these singleton objects have been instantiated

// at this point, and in any case it is not desirable to introduce

// this dependancy into SlacDate.

System.err.println("JDK VERSION ERROR : Unsupported JDK - '" + jdk + "' provided by '" + vendor + "'. SlacDate class requires examination.");

}

*/

}

}

}

/**

* Construct the date with todays date.

*

*

This should be the only place where a Date object is explicitly instantiated. All

* other code should use SlacDate. If the s_adjustForBST flag is set and the date falls

* between the last sunday of March and the last Sunday of October (inclusive) then we need

* to make an adjustment of +1 hour so that British Summertime is correctly reported.

*/

private SlacDate()

{

init(Calendar.getInstance());

}

/**

* Construct the date with the specified day, month and year.

*

* @param year The year to set the date to

* @param month The month to set the date to

* @param date The date to set the date to

* @exception InvalidDateException Invalid date parameters passed in.

*/

public SlacDate(int year, int month, int date) throws InvalidDateException

{

init(year, month, date, DefaultHours, DefaultMinutes, DefaultSeconds, DefaultMillis);

}

/**

* Construct the date with the specified day, month, year, hour and minute.

*

* @param year The year to set the date to

* @param month The month to set the date to

* @param date The date to set the date to

* @param hr The hour to set the date to

* @param min The minute to set the date to

* @exception InvalidDateException Invalid date parameters passed in.

*/

public SlacDate(int year, int month, int date, int hr, int min) throws InvalidDateException

{

init(year, month, date, hr, min, DefaultSeconds, DefaultMillis);

}

/**

* Construct the date with the specified day, month, year, hour, minute and second.

* Will default to 0 milliseconds.

*

* @param year The year to set the date to

* @param month The month to set the date to

* @param date The date to set the date to

* @param hr The hour to set the date to

* @param min The minute to set the date to

* @param sec The second to set the date to

* @exception InvalidDateException Invalid date parameters passed in.

*/

public SlacDate(int year, int month, int date, int hr, int min, int sec) throws InvalidDateException

{

init(year, month, date, hr, min, sec, DefaultMillis);

}

/**

* Construct the date with the specified day, month, year, hour, minute, second and milliseconds.

*

* @param year The year to set the date to

* @param month The month to set the date to

* @param date The date to set the date to

* @param hr The hour to set the date to

* @param min The minute to set the date to

* @param sec The second to set the date to

* @param millis The milliseconds to set the date to

* @exception InvalidDateException Invalid date parameters passed in.

*/

public SlacDate(int year, int month, int date, int hr, int min, int sec, int millis) throws InvalidDateException

{

init(year, month, date, hr, min, sec, millis);

}

/**

* Construct the date from a timestamp.

*/

public SlacDate(long timestamp) throws InvalidDateException

{

Calendar cal = Calendar.getInstance();

cal.setTime(new Date(timestamp));

init(cal);

}

/**

* Construct the date from the specified string. Note that the date must

* be in day/month/year format.

*

* @param date The date string.

* @exception InvalidDateException The date passed in is invalid.

*/

public SlacDate(String date) throws InvalidDateException

{

init(date);

}

/**

* Construct the date from the specified string. The format passed in will

* identify the format of the date.

*

* @param date The date string.

* @param format The format of the date.

* @exception InvalidDateException The date passed in is invalid.

*/

public SlacDate(String date, int format) throws InvalidDateException

{

if (format == FormatCCYYMMDD || format == FormatCCYYMMDDHHMM || format == FormatCCYYMMDDHHMMSS)

{

boolean valid = false;

date = date.trim();

if (date.length() >= 8)

{

try

{

int year = Integer.parseInt(date.substring(0,4));

int month = Integer.parseInt(date.substring(4,6));

int day = Integer.parseInt(date.substring(6,8));

int hour;

int min;

int sec;

if (date.length() > 8)

{

hour = Integer.parseInt(date.substring(8,10));

min = Integer.parseInt(date.substring(10,12));

if (date.length() >= 14)

sec = Integer.parseInt(date.substring(12,14));

else

sec = DefaultSeconds;

}

else

{

hour = DefaultHours;

min = DefaultMinutes;

sec = DefaultSeconds;

}

init(year, month, day, hour, min, sec, DefaultMillis);

valid = true;

}

catch (Exception e)

{

}

}

if (!valid)

throw new InvalidDateException("Invalid date: " + date + " for the specified format");

}

else if (format == FormatDB2TIMESTAMP || format == FormatUDBTIMESTAMP)

{

// 2002-02-04 10:49:30.999000 (UDB)

// 2002-02-04-10.49.30.999000 (DB2)

int year = Integer.parseInt(date.substring(0,4));

int month = Integer.parseInt(date.substring(5,7));

int day = Integer.parseInt(date.substring(8,10));

int hour = Integer.parseInt(date.substring(11,13));

int min = Integer.parseInt(date.substring(14,16));

int sec = Integer.parseInt(date.substring(17,19));

int millis = Integer.parseInt(date.substring(20,23));

init(year, month, day, hour, min, sec, millis);

}

else

{

init(date);

}

}

/**

* Construct the date with the java.util.Date passed in.

*/

public SlacDate(Date date)

{

init(date);

}

/**

* Init the date with the java.util.Date passed in.

*/

private void init(Date date)

{

Calendar cal = Calendar.getInstance();

cal.setTime(date);

init(cal);

}

/**

* Return whether this date is after the date passed in.

*

* @d2 The date to compare against.

* @return Whether this date is after the date passed in.

*/

public boolean after(SlacDate d2)

{

int xx = d2.getYear();

if (m_yyyy > xx)

return true;

else if (m_yyyy < xx)

return false;

else

{

xx = d2.getMonth();

if (m_mm > xx)

return true;

else if (m_mm < xx)

return false;

else

{

xx = d2.getDate();

if (m_dd > xx)

return true;

else if (m_dd < xx)

return false;

else

{

xx = d2.getHour();

if (m_hh > xx)

return true;

else if (m_hh < xx)

return false;

else

{

xx = d2.getMinute();

if (m_min > xx)

return true;

else if (m_min < xx)

return false;

else

{

xx = d2.getSecond();

if (m_ss > xx)

return true;

else if (m_ss < xx)

return false;

else

return (m_mil > d2.getMillisecond());

}

}

}

}

}

}

private void appendHoursMinutes(StringBuffer str, String separator)

{

if (m_hh < 10)

str.append(ZERO);

str.append(Integer.toString(m_hh));

if (!separator.equals(EMPTY))

str.append(separator);

if (m_min < 10)

str.append(ZERO);

str.append(Integer.toString(m_min));

}

private void appendTime(StringBuffer str, String separator, boolean addMillis)

{

appendHoursMinutes(str, separator);

if (!separator.equals(EMPTY))

str.append(separator);

if (m_ss < 10)

str.append(ZERO);

str.append(Integer.toString(m_ss));

if (addMillis)

{

if (!separator.equals(EMPTY))

str.append(separator);

if (m_mil < 100)

{

str.append(ZERO);

if (m_mil < 10)

str.append(ZERO);

}

str.append(m_mil);

}

}

/**

* Version of the asString() method which defaults to FormatDDMMCCYY.

*

*

An example date in this format is:

* <pre>

*25-02-1999

* </pre>

*

* @return The Date as a string in DDMMCCYY format.

*/

public String asString()

{

return asString(FormatDDMMCCYY);

}

/**

* Convert the date to a String. This will format the Date as defined by the format

* passed in. The default parameter is FormatDDMMCCYY.

*

* The valid formats are:

* <ul>

* <li>FormatDDMMCCYY</li>

* <li>FormatMMDDCCYY</li>

* <li>FormatDATETIME</li>

* <li>FormatDDMMTIME</li>

* <li>FormatTIMESTAMP</li>

* <li>FormatCCYYMMDD</li>

* <li>FormatCCYYMMDDHHMM</li>

* <li>FormatCCYYMMDDHHMMSS</li>

* <li>FormatDDMMCCYYTIME</li>

* <li>FormatDATEVERBOSE</li>

* <li>FormatDATETIMEVERBOSE</li>

* <li>FormatHHMMSS</li>

* <li>FormatHHMMSSMIL</li>

* <li>FormatDB2TIMESTAMP</li>

* <li>FormatUDBTIMESTAMP</li>

* </ul>

*

* @param format The format to return the string in.

* @return The date in string format (as specified by the format parameter).

*/

public String asString(int format)

{

StringBuffer str = new StringBuffer(20);

if (format == FormatDB2TIMESTAMP || format == FormatUDBTIMESTAMP)

{

str.append(Integer.toString(getYear()));

str.append(HYPHEN);

int month = getMonth();

if (month < 10)

str.append(ZERO);

str.append(Integer.toString(month));

str.append(HYPHEN);

int day = getDate();

if (day < 10)

str.append(ZERO);

str.append(Integer.toString(day));

String dateTimeSeparator = new String();

if (format == FormatDB2TIMESTAMP)

dateTimeSeparator = HYPHEN;

else if (format == FormatUDBTIMESTAMP)

dateTimeSeparator = SPACE;

str.append(dateTimeSeparator);

String timeSeparator = new String();

if (format == FormatDB2TIMESTAMP)

timeSeparator = PERIOD;

else if (format == FormatUDBTIMESTAMP)

timeSeparator = COLON;

appendTime(str, timeSeparator, true);

str.append("000");

}

else if (format == FormatDATETIME || format == FormatMMMDDTIME || format == FormatTIMESTAMP)

{

str.append(getMonthNameAbbrev());

str.append(SPACE);

if (m_dd < 10)

str.append(ZERO);

str.append(Integer.toString(m_dd));

str.append(SPACE);

appendTime(str, COLON, false);

if (format == FormatDATETIME)

{

str.append(SPACE);

str.append(Integer.toString(m_yyyy));

}

else if (format == FormatTIMESTAMP)

{

str.append(COLON);

str.append(formattedMillis(m_mil));

}

}

else if (format == FormatHHMMSS)

{

appendTime(str, COLON, false);

}

else if (format == FormatHHMMSSMIL)

{

appendTime(str, COLON, true);

}

else if (format == FormatCCYYMMDD || format == FormatCCYYMMDDHHMM || format == FormatCCYYMMDDHHMMSS)

{

str.append(Integer.toString(m_yyyy));

if (m_mm < 10)

str.append(ZERO);

str.append(Integer.toString(m_mm));

if (m_dd < 10)

str.append(ZERO);

str.append(Integer.toString(m_dd));

if (format == FormatCCYYMMDDHHMMSS)

appendTime(str, EMPTY, false);

else if (format == FormatCCYYMMDDHHMM)

appendHoursMinutes(str, EMPTY);

}

else if (format == FormatDATEVERBOSE || format == FormatDATETIMEVERBOSE)

{

str.append(Integer.toString(m_dd));

if (m_dd > 10 && m_dd < 14)

str.append(DayExtension[0]);

else

str.append(DayExtension[m_dd%10]);

str.append(SPACE);

str.append(getMonthName());

str.append(SPACE);

str.append(Integer.toString(m_yyyy));

if (format == FormatDATETIMEVERBOSE)

{

str.append(",");

str.append(SPACE);

appendTime(str, COLON, false);

}

}

else

{

// DDMMCCYY, MMDDCCYY, DDMMCCYYTIME

int first;

int second;

if (format != FormatMMDDCCYY)

{

first = getDate();

second = getMonth();

}

else

{

second = getDate();

first = getMonth();

}

if (first < 10)

str.append(ZERO);

str.append(Integer.toString(first));

str.append(s_dateSep);

if (second < 10)

str.append(ZERO);

str.append(Integer.toString(second));

str.append(s_dateSep);

str.append(Integer.toString(getYear()));

if (format == FormatDDMMCCYYTIME)

{

str.append(SPACE);

appendTime(str, COLON, false);

}

}

return str.toString();

}

/**

* Return whether this date is before the date passed in

*

* @d2 The date to compare against.

* @return Whether this date is before the date passed in.

*/

public boolean before(SlacDate d2)

{

return (!after(d2) && !equals(d2));

}

/**

* Clone the current date.

*

* @return The cloned SlacDate object

*/

public Object clone()

{

SlacDate d = new SlacDate();

d.m_dd= m_dd;

d.m_mm= m_mm;

d.m_yyyy= m_yyyy;

d.m_hh= m_hh;

d.m_min= m_min;

d.m_ss= m_ss;

d.m_mil= m_mil;

return d;

}

/**

* Compare this date with the supplied date.

* Hours, minutes, seconds and milliseconds are taken into consideration.

* Returns:

* -1 this date is before the supplied date.

* 0 this date is equal to the supplied date.

* 1 this date is after the supplied date.

*/

public int compareTo(Object o2)

{

SlacDate d2 = (SlacDate)o2;

if (equals(d2))

return 0;

if (after(d2))

return 1;

return -1;

}

/**

* Compare this date with the supplied date.

* Hours, minutes, seconds and milliseconds are NOT taken into consideration.

* Returns:

* -1 this date is before the supplied date.

* 0 this date is equal to the supplied date.

* 1 this date is after the supplied date.

*/

public int compareDate(Object o2)

{

SlacDate baseDate = (SlacDate)o2;

SlacDate startBaseDate = new SlacDate(baseDate.getCalendar().getTime());

startBaseDate.setHour(0);

startBaseDate.setMinute(0);

startBaseDate.setSecond(0);

startBaseDate.setMillisecond(0);

SlacDate endBaseDate = new SlacDate(baseDate.getCalendar().getTime());

endBaseDate.setHour(23);

endBaseDate.setMinute(59);

endBaseDate.setSecond(59);

endBaseDate.setMillisecond(999);

int compare = 0;

if (before(startBaseDate))

{

compare = -1;

}

else if (after(endBaseDate))

{

compare = 1;

}

return compare;

}

/**

* Compare this date with today's date.

* Hours, minutes, seconds and milliseconds are NOT taken into consideration.

* Returns:

* -1 this date is before today.

* 0 this date is equal to today.

* 1 this date is after today.

*/

public int compareToToday()

{

return compareDate(today());

}

/**

* Calculate the difference (in days) between the two dates.

* Note the difference may be negative.

*

* @param from The <i>start</i> date

* @param to The <i>to</i> date

* @return The difference between the dates in days.

*/

public static int daysBetween(SlacDate from, SlacDate to)

{

int dayFrom;

intmonthFrom;

int yrFrom;

int dayTo;

intmonthTo;

int yrTo;

int mult = 1;

if (from.after(to))

{

mult=-1;

dayFrom= to.getDate();

monthFrom= to.getMonth();

yrFrom= to.getYear();

dayTo= from.getDate();

monthTo= from.getMonth();

yrTo= from.getYear();

}

else

{

dayFrom= from.getDate();

monthFrom= from.getMonth();

yrFrom= from.getYear();

dayTo= to.getDate();

monthTo= to.getMonth();

yrTo= to.getYear();

}

int cnt=0;

try

{

if (yrFrom != yrTo)

{

// Different Years.

for (int i=yrFrom+1; i<yrTo; i++)

cnt += SlacDate.daysInYear(i);

for (int i=monthFrom+1; i><13; i++)

cnt+=daysInMonth(i, yrFrom);

for (int i=1; i<monthTo; i++)

cnt+=daysInMonth(i, yrTo);

cnt += (daysInMonth(monthFrom, yrFrom)-dayFrom);

cnt += dayTo;

}

else

{

if (monthFrom != monthTo)

{

// Same Year but different months.

for (int i=monthFrom+1; i><monthTo; i++)

cnt+=daysInMonth(i, yrFrom);

cnt += (daysInMonth(monthFrom, yrFrom)-dayFrom);

cnt += dayTo;

}

else

{

// Same Year and month.

cnt += (dayTo-dayFrom);

}

}

}

catch (InvalidDateException ide)

{

// This should never happen

}

return cnt * mult;

}

/**

* Calculate the number of days from the specified date.

* Note the difference may be negative.

*

* @param date The date to calculate from

* @return The diference between the two dates in days (may be negative).

*/

public int daysFrom(SlacDate date)

{

return daysBetween(date, this);

}

/**

* Calculates the number of days in a given month in a given year

* copes with century dates!

*

* @param month The month to determine the day count

* @param year The year the month is in (only relevant for February).

* @exception InvalidDateException Invalid parameters passed in. Ie the month was >= 12

*or the month was < 0.

*/

public static int daysInMonth(int month, int year) throws InvalidDateException

{

if (month > 12 || month <= 0)

throw new InvalidDateException("Invalid month specified to SlacDate.daysInMonth(): " + month);

// month-1, because DaysInMonth array is 0-based.

return (month == FEBRUARY && isLeapYear(year)) ? 29 : DaysInMonth[month-1];

}

/**

* Calculates the number of days in a given year.

*

* @param year The year the month is in (only relevant for February).

*/

public static int daysInYear(int year)

{

return (isLeapYear(year)) ? 365 : 364;

}

/**

* Calculate the number of days to the specified date.

* Note the difference may be negative.

*

* @param date The date to calculate to

* @return The diference between the two dates in days (may be negative).

*/

public int daysTo(SlacDate date)

{

return daysBetween(this, date);

}

/**

* Decrement the date by the specified number of years, months and days.

*

* @param years The number of years to increment by

* @param months The number of months to increment by

* @param days The number of days to increment by

*/

public void decrement(int years, int months, int days)

{

decrementYears(years);

decrementMonths(months);

decrementDays(days);

}

/**

* Decrement the date by the specified number of days.

*

* @param days The number of days to decrement by

*/

public void decrementDays(int days)

{

incrementDays(days * -1);

}

/**

* Decrement the date by the specified number of hours.

*

* @param hours The number of hours to decrement by

*/

public void decrementHours(int hours)

{

incrementHours(hours * -1);

}

/**

* Decrement the date by the specified number of milliseconds.

*

* @param seconds The number of seconds to decrement by

*/

public void decrementMilliseconds(int milliseconds)

{

incrementMilliseconds(milliseconds * -1);

}

/**

* Decrement the date by the specified number of minutes.

*

* @param minutes The number of minutes to decrement by

*/

public void decrementMinutes(int minutes)

{

incrementMinutes(minutes * -1);

}

/**

* Decrement the date by the specified number of months.

*

* @param years The number of months to decrement by

*/

public void decrementMonths(int months)

{

incrementMonths(months * -1);

}

/**

* Decrement the date by the specified number of seconds.

*

* @param seconds The number of seconds to decrement by

*/

public void decrementSeconds(int seconds)

{

incrementSeconds(seconds * -1);

}

/**

* Decrement the date by the specified number of years.

*

* @param years The number of years to decrement by

*/

public void decrementYears(int years)

{

incrementYears(years * -1);

}

/**

* Calculate the difference between two dates to the nearest second as a String.

*

* @param from The start date

* @param to The end date

*/

public static String differenceBetween(SlacDate from, SlacDate to)

{

SlacDate f, t;

if (from.after(to))

{

t = from;

f = to;

}

else

{

t = to;

f = from;

}

int secs= 0;

int mins= 0;

int hours = 0;

int days= 0;

int months = 0;

int years = 0;

secs= t.getSecond() - f.getSecond();

mins= t.getMinute() - f.getMinute();

hours= t.getHour()- f.getHour();

days= t.getDate()- f.getDate();

months= t.getMonth() - f.getMonth();

years= t.getYear()- f.getYear();

if (secs < 0)

{

secs += 60;

mins--;

}

if (mins < 0)

{

mins += 60;

hours--;

}

if (hours < 0)

{

hours += 24;

days--;

}

if (days < 0)

{

try

{

days += daysInMonth(f.getMonth(), f.getYear());

}

catch (InvalidDateException ide)

{

days += 30;

}

months--;

}

if (months < 0)

{

months += 12;

years--;

}

StringBuffer sb = new StringBuffer();

sb.append(years).append(s_dateSep);

sb.append(months).append(s_dateSep);

sb.append(days).append(SPACE);

sb.append(hours).append(COLON);

sb.append(mins).append(COLON);

sb.append(secs);

return sb.toString();

}

/**

* Calculate the difference between the date passed in and this date.

* Note that if the date passed in is in the future the difference will be

* negative.

*

* @param from The date from which to return the difference

* @return The difference from the date passed in in String format

*/

public String differenceFrom(SlacDate from)

{

return differenceBetween(from, this);

}

/**

* Calculate the difference between this date and the one passed in.

* Note that if the date passed in is in the past the difference will be

* negative.

*

* @param to The date to which to return the difference

* @return The difference to the date passed in in String format

*/

public String differenceTo(SlacDate to)

{

return differenceBetween(this, to);

}

/**

* Return whether the two dates are the same. This will check right down to the second.

*

* @param d2 The date to compare against

* @return Whether the dates are the same.

*/

public boolean equals(SlacDate d2)

{

return ((m_yyyy == d2.m_yyyy) &&

(m_mm == d2.m_mm) &&

(m_dd == d2.m_dd) &&

(m_hh == d2.m_hh) &&

(m_min == d2.m_min) &&

(m_ss == d2.m_ss) &&

(m_mil == d2.m_mil));

}

public String format(DateFormat df)

{

Calendar cal = getCalendar();

return df.format(cal.getTime());

}

private final String formattedMillis(int millis)

{

String rString = null;

if (millis < 10)

rString = "00" + millis;

else if (millis < 100)

rString = ZERO + millis;

else

rString = EMPTY + millis;

return rString;

}

public Calendar getCalendar()

{

Calendar cal = Calendar.getInstance();

cal.set(m_yyyy, m_mm-1, m_dd, m_hh, m_min, m_ss);

cal.set(Calendar.MILLISECOND, m_mil);

return cal;

}

/**

* Return the Date/Time in CCYYMMDD format.

*

*

An example date in this format is:

* <pre>

*19990225

* </pre>

*

* @return The Date as a string in CCYYMMDD format.

*/

public String getCCYYMMDD()

{

return asString(FormatCCYYMMDD);

}

/**

* Return the Date/Time in CCYYMMDDHHMM format.

*

*

An example date in this format is:

* <pre>

*199902251423

* </pre>

*

* @return The Date as a string in CCYYMMDDHHMM format.

*/

public String getCCYYMMDDHHMM()

{

return asString(FormatCCYYMMDDHHMM);

}

/**

* Return the Date/Time in CCYYMMDDHHMMSS format.

*

*

An example date in this format is:

* <pre>

*19990225142356

* </pre>

*

* @return The Date as a string in CCYYMMDDHHMMSS format.

*/

public String getCCYYMMDDHHMMSS()

{

return asString(FormatCCYYMMDDHHMMSS);

}

public int getDate(){ return m_dd; }

/**

* Return the date in DATETIME format.

*

*

An example date in this format is:

* <pre>

*Feb 25 14:21:09 1999

* </pre>

*

* @return The Date as a string in DATETIME format.

*/

public String getDATETIME()

{

return asString(FormatDATETIME);

}

/**

* Return the Date/Time in DATETIMEVERBOSE format.

*

*

An example date in this format is:

* <pre>

*25th February 1999, 14:21:09

* </pre>

*

* @return The Date as a string in DATETIMEVERBOSE format.

*/

public String getDATETIMEVERBOSE()

{

return asString(FormatDATETIMEVERBOSE);

}

/**

* Return the Date/Time in DATEVERBOSE format.

*

*

An example date in this format is:

* <pre>

*25th February 1999

* </pre>

*

* @return The Date as a string in DATEVERBOSE format.

*/

public String getDATEVERBOSE()

{

return asString(FormatDATEVERBOSE);

}

/**

* Return the day of the week.

*

* @return The day of the week.

*/

public int getDay()

{

Calendar cal = Calendar.getInstance();

cal.set(m_yyyy, m_mm-1, m_dd);

return cal.get(Calendar.DAY_OF_WEEK);

}

/**

* Return the day of the week as a string.

*

* @return The day of the week as a string.

*/

public String getDayName()

{

int dd = getDay()-1;

return DaysOfWeek[dd];

}

/**

* Get a string representation of the day passed in.

*

* @param day The day of the week to return as a string.

* @return The day of the week as a string.

*/

public static String getDayName(int day)

{

day = day-1 % DAYS_IN_WEEK;

return DaysOfWeek[day];

}

/**

* Return the day of the week as a string.

*

* @return The day of the week as a string.

*/

public String getDayNameAbbrev()

{

int dd = getDay()-1;

return DaysOfWeekAbbrev[dd];

}

/**

* Return the day of the week as a string.

*

* @return The day of the week as a string.

*/

public static String getDayNameAbbrev(int day)

{

int dd = day-1;

return DaysOfWeekAbbrev[dd];

}

/**

* Return the Date/Time in DB2TIMESTAMP format.

*

*

An example date in this format is:

* <pre>

*2002-02-25 14:21:09:014000

* </pre>

*

* @return The Date as a string in DB2TIMESTAMP format.

*/

public String getDB2TIMESTAMP()

{

return asString(FormatDB2TIMESTAMP);

}

/**

* Return the Date/Time in DDMMCCYYTIME format.

*

*

An example date in this format is:

* <pre>

*25-02-1999 14:21:09

* </pre>

*

* @return The Date as a string in DDMMCCYYTIME format.

*/

public String getDDMMCCYYTIME()

{

return asString(FormatDDMMCCYYTIME);

}

public int getHour(){ return m_hh; }

/**

* @depreacted Use getMillisecond instead.

*/

public int getMillisecond(){ return m_mil; }

public int getMinute(){ return m_min; }

/**

* Return the Date/Time in MMDDCCYY format.

*

*

An example date in this format is:

* <pre>

*02-25-1999

* </pre>

*

* @return The Date as a string in MMDDCCYY format.

*/

public String getMMDDCCYY()

{

return asString(FormatMMDDCCYY);

}

public int getMonth(){ return m_mm; }

/**

* Return the month as a string.

*

* @return The month as a string.

*/

public String getMonthName()

{

return MonthVerbose[m_mm-1];

}

/**

* Return the month as a string.

*

* @param month The month of the year to return as a string.

* @return The month as a string.

*/

public static String getMonthName(int month)

{

month = (month - 1) % MONTHS_IN_YEAR;

return MonthVerbose[month];

}

/**

* Return the month as a string.

*

* @return The month as a string.

*/

public String getMonthNameAbbrev()

{

return MonthAbbrev[m_mm-1];

}

/**

* Return the month as a string.

*

* @param month The month of the year to return as a string.

* @return The month as a string.

*/

public static String getMonthNameAbbrev(int month)

{

month = (month - 1) % MONTHS_IN_YEAR;

return MonthAbbrev[month];

}

/**

* Get the next Date with the day passed in. Ie return me the next date which is

* a friday. If the current date is friday then the next friday (ie 7 days from now)

* will be returned.

*

* @param day the day in the week.

* @exception InvalidDateException Should not really happen.

*/

public SlacDate getNextDay(int day) throws InvalidDateException

{

if (day < SUNDAY || day > SATURDAY)

throw new IllegalArgumentException("Invalid day of week. Must be in range 1 (sun) - 7 (sat)");

SlacDate d = (SlacDate)clone();

int thisDay = getDay();

int inc;

if (day == thisDay)

inc = DAYS_IN_WEEK;

else if (day > thisDay)

inc = day - thisDay;

else

inc = DAYS_IN_WEEK - (thisDay - day);

d.incrementDays(inc);

return d;

}

public int getSecond(){ return m_ss; }

/**

* Version of the asString() method which defaults to FormatDDMMCCYY.

*

* @return The Date as a string in DDMMCCYY format.

*/

public String getTime()

{

StringBuffer str = new StringBuffer();

appendTime(str, COLON, false);

return str.toString();

}

/**

* Return the Date/Time in TIMESTAMP format.

*

*

An example date in this format is:

* <pre>

*Feb 25 14:21:09:014

* </pre>

*

* @return The Date as a string in TIMESTAMP format.

*/

public String getTIMESTAMP()

{

return asString(FormatTIMESTAMP);

}

public int getYear(){ return m_yyyy; }

/**

* Return a unique hash code for this object.

*

* @return The hashcode for this date object.

*/

public int hashCode()

{

StringBuffer str = new StringBuffer();

str.append(Integer.toString(m_dd));

str.append(s_dateSep);

str.append(Integer.toString(m_mm));

str.append(s_dateSep);

str.append(Integer.toString(m_yyyy));

str.append(SPACE);

str.append(Integer.toString(m_hh));

str.append(COLON);

str.append(Integer.toString(m_min));

str.append(COLON);

str.append(Integer.toString(m_ss));

return str.toString().hashCode();

}

/**

* Increment the date by the specified number of years, months and days.

*

* @param years The number of years to increment by

* @param months The number of months to increment by

* @param days The number of days to increment by

*/

public void increment(int years, int months, int days)

{

incrementYears(years);

incrementMonths(months);

incrementDays(days);

}

/**

* Increment the date by the specified number of days.

*

* @param days The number of days to increment by

*/

public void incrementDays(int days)

{

if (days != 0)

{

try

{

if (days < 0) // i.e. a decrement

{

days *= -1;

for (int x = 1; x <= days; x++)

{

int dd = getDate();

if (dd == 1)

{

decrementMonths(1);

setDate(daysInMonth(getMonth(), getYear()));

}

else

{

setDate(dd - 1);

}

}

}

else // i.e. an increment

{

for (int x = 1; x <= days; x++)

{

int dd = getDate();

if (dd == daysInMonth(getMonth(), getYear()))

{

setDate(1);

incrementMonths(1);

}

else

{

setDate(dd + 1);

}

}

}

}

catch (Exception e)

{

throw new UnsupportedOperationException("SlacDate.incrementDays-> This should never happen: " + e.toString());

}

}

}

/**

* Increment the date by the specified number of hours.

*

* @param hours The number of hours to increment by

*/

public void incrementHours(int hours)

{

if (hours != 0)

{

try

{

if (hours < 0) // i.e. a decrement

{

hours *= -1;

for (int x = 1; x <= hours; x++)

{

int hh = getHour();

if (hh == 0)

{

decrementDays(1);

setHour(23);

}

else

{

setHour(hh - 1);

}

}

}

else // i.e. an increment

{

for (int x = 1; x <= hours; x++)

{

int hh = getHour();

if (hh == 23)

{

setHour(0);

incrementDays(1);

}

else

{

setHour(hh + 1);

}

}

}

}

catch (Exception e)

{

throw new UnsupportedOperationException("SlacDate.incrementHours-> This should never happen: " + e.toString());

}

}

}

/**

* Increment the date by the specified number of milliseconds.

*

* @param seconds The number of milliseconds to increment by

*/

public void incrementMilliseconds(int milliseconds)

{

// @@@ This should be optimized.....

if (milliseconds != 0)

{

if (milliseconds < 0) // i.e. a decrement

{

milliseconds *= -1;

{

int mm = milliseconds / 1000;

if (mm > 0)

{

decrementSeconds(mm);

milliseconds -= (mm * 1000);

}

}

for (int x = 1; x <= milliseconds; x++)

{

if (getMillisecond() == 0)

{

decrementSeconds(1);

setMillisecond(999);

}

else

{

setMillisecond(getMillisecond() - 1);

}

}

}

else // i.e. an increment

{

{

int mm = milliseconds / 1000;

if (mm > 0)

{

incrementSeconds(mm);

milliseconds -= (mm * 1000);

}

}

for (int x = 1; x <= milliseconds; x++)

{

if (getMillisecond() == 999)

{

setMillisecond(0);

incrementSeconds(1);

}

else

{

setMillisecond(getMillisecond() + 1);

}

}

}

}

}

/**

* Increment the date by the specified number of minutes.

*

* @param minutes The number of minutes to increment by

*/

public void incrementMinutes(int minutes)

{

if (minutes != 0)

{

try

{

if (minutes < 0) // i.e. a decrement

{

minutes *= -1;

for (int x = 1; x <= minutes; x++)

{

int mm = getMinute();

if (mm == 0)

{

decrementHours(1);

setMinute(59);

}

else

{

setMinute(mm - 1);

}

}

}

else // i.e. an increment

{

for (int x = 1; x <= minutes; x++)

{

int mm = getMinute();

if (mm == 59)

{

setMinute(0);

incrementHours(1);

}

else

{

setMinute(mm + 1);

}

}

}

}

catch (Exception e)

{

throw new UnsupportedOperationException("SlacDate.incrementMinutes-> This should never happen: " + e.toString());

}

}

}

/**

* Increment the date by the specified number of months.

*

* @param years The number of months to increment by

*/

public void incrementMonths(int months)

{

if (months != 0)

{

intdate= getDate();

intyr= getYear();

intmonth= getMonth();

inttotMonths = months + month;

if (totMonths == 0)

{

month = 12;

yr--;

}

else if (totMonths < 0)

{

months *= -1;

if (months > 12)

{

yr -= months / 12;

months = months % 12;

}

if (month - months <= 0)

{

yr--;

month = 12 - (months - month);

}

else

{

month -= months;

}

}

else

{

if (totMonths > 12)

yr += ((totMonths-1) / 12);// add years

month = totMonths % 12;// add remaining months

if (month == 0)

month = 12;

}

try

{

// Just in case we jump a month from Mar31 to Apr31 which does not exist.

int daysThisMonth = daysInMonth(month, yr);

date = Math.min(date, daysThisMonth);

setDate(date);

setMonth(month);

setYear(yr);

}

catch (InvalidDateException e)

{

throw new UnsupportedOperationException("SlacDate.incrementMonths-> This should never happen: " + e.toString());

}

}

}

/**

* Increment the date by the specified number of seconds.

*

* @param seconds The number of seconds to increment by

*/

public void incrementSeconds(int seconds)

{

if (seconds != 0)

{

if (seconds < 0) // i.e. a decrement

{

seconds *= -1;

for (int x = 1; x <= seconds; x++)

{

if (getSecond() == 0)

{

decrementMinutes(1);

setSecond(59);

}

else

{

setSecond(getSecond() - 1);

}

}

}

else // i.e. an increment

{

for (int x = 1; x <= seconds; x++)

{

if (getSecond() == 59)

{

setSecond(0);

incrementMinutes(1);

}

else

{

setSecond(getSecond() + 1);

}

}

}

}

}

/**

* Increment the date by the specified number of years.

*

* @param years The number of years to increment by

*/

public void incrementYears(int years)

{

if (years != 0)

{

int day= getDate();

intmonth= getMonth();

int yr= getYear() + years;

// We need to check that we are not incrementing from the 29th of February

// on a non leap-year to a leap-year.

if (month == 2 && day == 29 && !isLeapYear(yr))

m_dd = 28;

m_yyyy = yr;

}

}

private void init(int year, int month, int date, int hr, int min, int sec, int millis) throws InvalidDateException

{

if (!validate(year, month, date, hr, min, sec, millis))

throw new InvalidDateException("Invalid date - " + year + s_dateSep + month + s_dateSep + date + SPACE + hr + COLON + min + COLON + sec);

/*

try

{

Calendar cal = Calendar.getInstance();

cal.set(year, month-1, date, hr, min, sec);

init(cal);

}

catch (Exception e)

{

throw new InvalidDateException(e.getMessage());

}

*/

m_yyyy= year;

m_mm= month;

m_dd= date;

m_hh= hr;

m_min= min;

m_ss= sec;

m_mil = millis;

}

private void init(String date) throws InvalidDateException

{

int day= 1;

int year= 0;

int month= 1;

int hh= DefaultHours;

int min= DefaultMinutes;

int ss= DefaultSeconds;

int mil= 0;

boolean isValid = false;

date = date.trim();

if (date.length() > 0)

{

if (Character.isLetter(date.charAt(0)))

{

// Assume it is one of the following formats:

//DATETIME: Dec 21 16:13:27 1998

//MMMDDTIME: Dec 21 16:13:27

//TIMESTAMP: Dec 21 16:13:27:089

try

{

StringTokenizer st = new StringTokenizer(date);

String _month = st.nextToken().toLowerCase().trim();

month = MONTHS_IN_YEAR + 1; // Initialise to invalid

for (int i = 0; i < MONTHS_IN_YEAR; i++)

{

if (_month.equals(MonthAbbrev[i].toLowerCase()))

{

month = i+1;

break;

}

}

day= Integer.parseInt(st.nextToken());

String _ts = st.nextToken();

if (st.hasMoreTokens())

year = Integer.parseInt(st.nextToken());

else

year = SlacDate.now().getYear();

st = new StringTokenizer(_ts, COLON);

hh= Integer.parseInt(st.nextToken());

min= Integer.parseInt(st.nextToken());

ss= Integer.parseInt(st.nextToken());

if (st.hasMoreTokens())

mil = Integer.parseInt(st.nextToken());

if (hh >= 0&& hh < 24&&

min >= 0&& min < 60&&

ss >= 0&& ss < 60&&

mil >= 0&& mil < 1000 &&

year > 1800)

{

isValid = true;

}

}

catch (Exception nse)

{

}

}

else

{

// Assume it is in the format: DD-MM-CCYY

int i= 0;

int j= 0;

int count= 0;

// Squash the string

{

StringBuffer buf = new StringBuffer(date.length());

for (int k = 0; k < date.length(); k++)

{

char c = date.charAt(k);

if (c != ' ' && c != '\t')

buf.append(c);

}

date = buf.toString();

}

// Return an invalid & null SlacDate if the SlacDate is invalid

if (date.length() != 0 && Character.isDigit(date.charAt(i)))

{

try

{

int length = date.length();

for (; i < length; j++)

{

if (!Character.isDigit(date.charAt(j)) || j == length-1)

{

// Need to make sure that a date like 12/03/x1947 is entered

if (j < length-2 && !Character.isDigit(date.charAt(j+1)))

{

isValid = false;

break;

}

Integer integer;

switch (count)

{

case 0:

day = Integer.parseInt(date.substring(i, j));

break;

case 1:

month = Integer.parseInt(date.substring(i, j));

break;

case 2:

try

{

year = Integer.parseInt(date.substring(i));

// Any date before 1800 in error. Used to ensure dates

// like 01/01/98 don't get through

if (year > 1800)

isValid = true;

}

catch (Exception e)

{

}

break;

default:

break;

}

if (2 == count || j == length)

break;

// Need to skip all remaining spaces

while (j < length && !Character.isDigit(date.charAt(j)))

j++;

// Make sure we have got more string to traverse

if (j >= length)

break;

// Fudge the indexes so that i points to the next number

i = j;

j--;

count++;

}

}

}

catch (Exception e)

{

isValid = false;

}

}

}

if (isValid)

{

if (year < 0 || month <= 0 || month > MONTHS_IN_YEAR || day <= 0 || day > daysInMonth(month, year))

isValid = false;

if (isValid)

{

m_yyyy= year;

m_mm= month;

m_dd= day;

m_hh= hh;

m_min= min;

m_ss= ss;

m_mil= mil;

}

}

}

if (!isValid)

{

throw new InvalidDateException("Invalid date: " + date);

}

}

private void init(Calendar d)

{

if (s_adjustForBST && isInBST(d))

{

d.add(Calendar.HOUR, 1);

}

m_yyyy= d.get(Calendar.YEAR);

m_mm= d.get(Calendar.MONTH)+1;

m_dd= d.get(Calendar.DAY_OF_MONTH);

m_hh= d.get(Calendar.HOUR_OF_DAY);

m_min= d.get(Calendar.MINUTE);

m_ss= d.get(Calendar.SECOND);

m_mil= d.get(Calendar.MILLISECOND);

}

public boolean isInBST()

{

return isInBST(getCalendar());

}

private boolean isInBST(Calendar d)

{

boolean bst = false;

int m = d.get(Calendar.MONTH);

int r = DaysInMonth[m] - d.get(java.util.Calendar.DAY_OF_MONTH);// Days left in Month

int c = d.get(java.util.Calendar.DAY_OF_WEEK)-1;// Current day of week (0 - 6)

if (m > 2 && m < 9 ||// Apr - Sep

m == 2 && !(r >= 7 || (r < 7 && (c+r > 6))) ||// On or after last sunday in mar

m == 9 && (r >= 7 || (r < 7 && (c+r > 6))))// Before last sunday in oct

{

bst = true;

}

return bst;

}

/**

* Returns whether a given year is a leap year.

*

* @param year The year to check whether it is a leap year

* @return Whether the year passed in is a leap year

*/

public static boolean isLeapYear(int year)

{

return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));

}

/**

* Return whether the string passed in represents a valid date.

* This is useful for validating that user input is valid. Note that

* any years before 1800 are invalid and the year must be represented

* in the four byte format.

*

* @param The date string to validate.

* @return Whether the date is in a valid format.

*/

public static boolean isValid(String dateAsString)

{

boolean valid = false;

try

{

new SlacDate(dateAsString);

valid = true;

}

catch (InvalidDateException e)

{

}

return valid;

}

/**

* Calculate the difference between two dates in millis.

*

* @param from The start date

* @param to The end date

*/

public static long millisecondsBetween(SlacDate from, SlacDate to)

{

SlacDate f, t;

long mult = 1;

if (from.after(to))

{

mult = -1;

t = from;

f = to;

}

else

{

t = to;

f = from;

}

int millis= t.getMillisecond() - f.getMillisecond();

int secs= t.getSecond() - f.getSecond();

int mins= t.getMinute() - f.getMinute();

int hours= t.getHour()- f.getHour();

int days= daysBetween(f, t);

if (millis < 0)

{

millis += 1000;

secs--;

}

if (secs < 0)

{

secs += 60;

mins--;

}

if (mins < 0)

{

mins += 60;

hours--;

}

if (hours < 0)

{

hours += 24;

days--;

}

long tt = millis +

(secs * MillisInSecond) +

(mins * MillisInMinute) +

(hours * MillisInHour) +

(days * MillisInDay);

return tt * mult;

}

/**

* Calculate the number of milliseconds from the specified date.

* Note the difference may be negative.

*

* @param date The date to calculate from

* @return The diference between the two dates in milliseconds (may be negative).

*/

public long millisecondsfrom(SlacDate date)

{

return millisecondsBetween(date, this);

}

/**

* Calculate the number of milliseconds to the specified date.

* Note the difference may be negative.

*

* @param date The date to calculate to

* @return The diference between the two dates in milliseconds (may be negative).

*/

public long millisecondsTo(SlacDate date)

{

return millisecondsBetween(this, date);

}

/**

* Returns the milliseconds portion of the current date

* @return The milliseconds portion of the current date

*/

private int millisNow()

{

long timeInMillis = System.currentTimeMillis();

int days = (int)(timeInMillis / MillisInDay);

long fract = timeInMillis - (days * MillisInDay);

int hours = (int)(fract / MillisInHour);

fract = fract - (hours * MillisInHour);

int minutes = (int)(fract / MillisInMinute);

fract = fract - (minutes * MillisInMinute);

int seconds = (int)(fract / 1000);

fract = fract - (seconds * 1000);

return (int)fract;

}

/**

* Return the date and time for NOW. This was done by the default constructor however it has now

* been made private to force people to call now() if they want a date and time object and to call

* today() if they want a date object only. I know its NAF but thats the Java Date class for you.

*

* @return The current date (to the millisecond).

*/

public static SlacDate now()

{

return new SlacDate();

}

/**

* Set the day of the month for his date.

*

* @param value The day of the month to set this date to

* @exception IllegalArgumentException Invalid day passed in

*/

public void setDate(int value) throws IllegalArgumentException

{

{

boolean ok = false;

try

{

ok = (value >= 1 && value <= daysInMonth(m_mm, m_yyyy));

}

catch (InvalidDateException de)

{

}

finally

{

if (!ok)

throw new IllegalArgumentException("Invalid date: " + value + s_dateSep + m_mm + s_dateSep + m_yyyy);

}

}

m_dd = value;

}

/**

* Allow for the date seperator to be overriden from the defaul '-'

*

* @param dateSep The date separator to use when printing dates

*/

public static void setDateSeperator(char dateSep)

{

char [] arr = new char[1];

arr[0] = dateSep;

s_dateSep = new String(arr);

}

/**

* Set the hour for this date.

*

* @param value The hour to set this date to

* @exception IllegalArgumentException Invalid hour passed in (must be >=0 and <= 23)

*/

public void setHour(int value) throws IllegalArgumentException

{

if (value < 0 || value > 23)

throw new IllegalArgumentException("Invalid hour specified: " + value);

m_hh = value;

}

/**

* Set the millisecond for this date.

*

* @param value The millisecond to set this date to

* @exception IllegalArgumentException Invalid millisecond passed in (must be >=0 and <= 999)

*/

public void setMillisecond(int value) throws IllegalArgumentException

{

if (value < 0 || value > 999)

throw new IllegalArgumentException("Invalid seconds specified: " + value);

m_mil = value;

}

/**

* Set the minute for this date.

*

* @param value The minute to set the date to

* @exception IllegalArgumentException Invalid minute passed in (must be >=0 and <= 59)

*/

public void setMinute(int value) throws IllegalArgumentException

{

if (value < 0 || value > 59)

throw new IllegalArgumentException("Invalid minutes specified: " + value);

m_min = value;

}

/**

* Set the month for this date.

*

* @param value The month to set this date to

* @exception IllegalArgumentException Invalid month passed in

*/

public void setMonth(int value) throws IllegalArgumentException

{

if (value > 12 || value < 1)

throw new IllegalArgumentException("The month " + value + " is invalid");

m_mm = value;

}

/**

* Set the second for this date.

*

* @param value The second to set this date to

* @exception IllegalArgumentException Invalid second passed in (must be >=0 and <= 59)

*/

public void setSecond(int value) throws IllegalArgumentException

{

if (value < 0 || value > 59)

throw new IllegalArgumentException("Invalid seconds specified: " + value);

m_ss = value;

}

/**

* Set the year for this date.

*

* @param value The year to set this date to

* @exception IllegalArgumentException Invalid year passed in

*/

public void setYear(int value) throws IllegalArgumentException

{

if (value < 1900)

throw new IllegalArgumentException("The year " + value + " is invalid (less than 1900)");

m_yyyy = value;

}

/**

* Return todays date with a uniform time. This will ensure that date

* comparisons do NOT take the time into consideration.

*

* @return The date for today. The time will be uniformly set to noon.

*/

public static SlacDate today()

{

SlacDate date = new SlacDate();

date.m_hh= DefaultHours;

date.m_min= DefaultMinutes;

date.m_ss= DefaultSeconds;

date.m_mil= DefaultMillis;

return date;

}

/**

* Return a String representation of the date.

* @return A String representation of the date.

*/

public String toString()

{

return asString();

}

private boolean validate(int year, int month, int date)

{

try

{

if (year > 1800 &&

month > 0 && month <= 12 &&

date > 0 &&

date <= daysInMonth(month, year))

{

return true;

}

}

catch (InvalidDateException e)

{

}

return false;

}

private boolean validate(int year, int month, int date, int hr, int min, int sec, int mil)

{

if (hr >= 0&& hr < 24&&

min >= 0&& min < 60&&

sec >= 0&& sec < 60&&

mil >= 0&& mil < 1000 &&

validate(year, month, date))

{

return true;

}

return false;

}

/**

* Calculate the difference (in years) between the two dates.

* Note the difference may be negative.

*

* @param from The <i>start</i> date

* @param to The <i>to</i> date

* @return The difference between the dates in years.

*/

public static int yearsBetween(SlacDate from, SlacDate to)

{

intdayFrom= from.getDate();

intmonthFrom= from.getMonth();

intyrFrom= from.getYear();

intdayTo= to.getDate();

intmonthTo= to.getMonth();

intyrTo= to.getYear();

intdifference = yrTo - yrFrom;

if ((dayFrom == dayTo) && (monthFrom == monthTo))

{

return difference;

}

if (monthFrom == monthTo)

{

if ((dayFrom < dayTo && difference >= 0) ||

(dayFrom > dayTo && difference < 0))

{

}

else

{

if (difference >= 0)

difference -= 1;

else

difference += 1;

}

}

else if (monthFrom > monthTo)

{

if ((monthFrom < monthTo && difference >= 0) ||

(monthFrom > monthTo && difference < 0))

{

}

else

{

if (difference >= 0)

difference -= 1;

else

difference += 1;

}

}

return difference;

}

/**

* Calculate the number of years from the specified date.

* Note the difference may be negative.

*

* @param date The date to calculate from

* @return The diference between the two dates in years (may be negative).

*/

public int yearsFrom(SlacDate date)

{

return yearsBetween(date, this);

}

/**

* Calculate the number of years to the specified date.

* Note the difference may be negative.

*

* @param date The date to calculate the years to

* @return The diference between the two dates in years (may be negative).

*/

public int yearsTo(SlacDate date)

{

return yearsBetween(this, date);

}

}

just pass Data as String and format u want

public String getCalendarDate()

{

SlacDate now = SlacDate.now();

String unique = now.asString(SlacDate.FormatCCYYMMDD);

return unique;

}

validate ...

avina_SMPPa at 2007-7-29 13:50:56 > top of Java-index,Java Essentials,Java Programming...
# 5

@avina_SMPP What the buggering hell is that?!?! And how does it help the OP?

c0demonk3ya at 2007-7-29 13:50:56 > top of Java-index,Java Essentials,Java Programming...
# 6

> i want validation for this format YYYY-MM-DDThh:mm:ss

What's that T