ProgramixGenericLib v5.0.1

com.programix.time
Class DateTools

java.lang.Object
  extended by com.programix.time.DateTools

public class DateTools
extends Object

Handy utilities for manipulating dates and times mostly focusing on DateTime and PlainDate.

Time translations (moving the Java VM into the past or future) and dilations (changing the speed that time runs) can be done by setting an alternate DateTools.TimeSource and then using the methods on this class for retrieving the current time. The simplest way to get the potentially alternate 'now' can be achieved by calling getTime() for a long and getNow() for a DateTime. By default, the TimeSource simply returns the normal time from System.currentTimeMillis().

Time Information
For more on time, various systems for time measurement, time zones, daylight saving time, leaps years, and leap seconds, visit some of the following sites.

Time Measurement:
US Navy - Time Service
US Navy - Systems of Time
Wikipedia - UTC (Coordinated Universal Time)
Wikipedia - UT (Universal Time)
Wikipedia - GMT (Greenwich Mean Time)
Time Zones:
Wikipedia - Time Zone
DateAndTime.com - Time Zones
Daylight Saving Time:
Wikipedia - Daylight Saving Time
DateAndTime.com - Daylight Saving Time
Leap Years:
Wikipedia - Leap Year
DateAndTime.com - Leap Years
Leap Seconds:
Wikipedia - Leap Second
US Navy - Leap Seconds
DateAndTime.com - Leap Seconds
Formatting the Date and Time:
International Organization for Standards - ISO 8601
Markus Kuhn - Summary of ISO 8601
W3C - Date and Time Formats
Wikipedia - Calendar Date Formats
HackCraft - Date and Time Formats on the Web

Time Zone Issues
Time zones can add a strange dimension to calculating what time of day it is—and even what day it is. Currently (2006) there are many time zones with many local peculiarities. They span from UTC-12 through UTC+14 making a maximum gap of 26 hours between two locations at the same moment in time. Daylight Saving Time (DST) is observed in some locations and not in others. DST changes the gap between the local time and UTC from its 'normal' winter-time gap. London is on UTC+0 and in the winter is aligned with UTC, but in the summer London is one hour ahead of UTC. In the United States, DST has changed many times. In the US, DST expands in 2007 to start on the second Sunday in March and to continue through the first Sunday of November (to determine if March 21 is or is not on DST, one must also know the year). Some locations are not whole hour amounts offset from UTC. The table below shows some time zone extremes. Note that when it is 2006-12-21 10:30 UTC, it is Dec 20 in one place, Dec 21 in another, and Dec 22 is yet another. If three people where in those places and on a conference call, they would have three different answers to the question of what "today" is!

UTC-11 UTC-6 UTC UTC UTC+14
Pacific/
Pago_Pago
America/
Chicago
UTC Europe/
London
Pacific/
Kiritimati
2006-12-21 01:00 2006-12-21 06:00 2006-12-21 12:00 2006-12-21 12:00 2006-12-22 02:00
2006-12-20 23:30 2006-12-21 04:30 2006-12-21 10:30 2006-12-21 10:30 2006-12-22 00:30
2006-06-21 01:00 2006-06-21 07:00 2006-06-21 12:00 2006-06-21 13:00 2006-06-22 02:00
2006-06-20 23:30 2006-06-21 05:30 2006-06-21 10:30 2006-06-21 11:30 2006-06-22 00:30

Author:
Paul Hyde
See Also:
PlainDate, PlainDateRange, DayOfWeek, DateTime, DateTimeRange, DateTimeFormat

Nested Class Summary
static class DateTools.AcceleratedTimeSource
          Used to speed forward from 'now' to a specified time in the future.
static class DateTools.OffsetTimeSource
          Used to specify an offset (positive or negative) from 'now' that should be used for the DateTools.TimeSource.
static interface DateTools.TimeSource
          Used to specify the source to use for milliseconds since Jan 1, 1970.
 
Field Summary
static DateTools.TimeSource DEFAULT_TIME_SOURCE
          This implementation of DateTools.TimeSource simply returns the time from the OS by using System.currentTimeMillis().
static long MS_PER_DAY
          Typical number of milliseconds in a day (86,400,000).
static long MS_PER_HOUR
          Typical number of milliseconds in an hour (3,600,000).
static long MS_PER_MINUTE
          Typical number of milliseconds in a minute (60,000).
static long MS_PER_SECOND
          Number of milliseconds in a second (1,000).
static long MS_PER_WEEK
          Typical number of milliseconds in a week (604,800,000).
 
Method Summary
static DateTime addDays(DateTime startTime, int numberOfDays)
           
static DateTime addDays(DateTime startTime, int numberOfDays, TimeZone tz)
           
static PlainDate addDays(PlainDate startDate, int numberOfDays)
          Adds the specified number of days to the specified startDate.
static DateTime addDaysLocal(DateTime startTime, int numberOfDays)
           
static PlainDate addDaysUntil(PlainDate startDate, DayOfWeek targetDayOfWeek)
          Adds days (as needed) to roll the specified startDate forward until the specified targetDayOfWeek is matched.
static DateTime addDaysUTC(DateTime startTime, int numberOfDays)
           
static DateTime addHours(DateTime startTime, int numberOfHours)
          Returns a new DateTime shifted by the specified number of hours.
static DateTime addMilliseconds(DateTime startTime, int numberOfMilliseconds)
          Returns a new DateTime shifted by the specified number of milliseconds.
static DateTime addMinutes(DateTime startTime, int numberOfMinutes)
          Returns a new DateTime shifted by the specified number of minutes.
static PlainDate addMonths(PlainDate startDate, int numberOfMonths)
          Adds the specified number of months to the specified startDate.
static DateTime addSeconds(DateTime startTime, int numberOfSeconds)
          Returns a new DateTime shifted by the specified number of seconds.
static PlainDate addWeeks(PlainDate startDate, int numberOfWeeks)
          Adds the specified number of weeks to the specified startDate.
static PlainDate addYears(PlainDate startDate, int numberOfYears)
          Adds the specified number of years to the specified startDate.
static double calculateDayDifference(DateTime startTime, DateTime endTime)
          Calculated the number of days from the startTime to the endTime.
static String format(DateTimeFormat dtf, DateTime dateTime, TimeZone tz)
          Formats the specified DateTime for the specified timezone.
static String format(DateTime dateTime, TimeZone tz)
          Formats the specified DateTime for the specified timezone.
static String format(String formatPattern, DateTime dateTime, TimeZone tz)
          Formats the specified DateTime for the specified timezone using the specified pattern.
static String formatLocal(DateTime dateTime)
          Formats the specified DateTime for the VM's timezone.
static String formatLocal(DateTimeFormat dtf, DateTime dateTime)
          Formats the specified DateTime for the VM's timezone.
static String formatLocal(String formatPattern, DateTime dateTime)
          Formats the specified DateTime for the VM's timezone using the specified pattern.
static String formatUTC(DateTime dateTime)
          Formats the specified DateTime for the UTC timezone.
static String formatUTC(DateTimeFormat dtf, DateTime dateTime)
          Formats the specified DateTime for the UTC timezone.
static String formatUTC(String formatPattern, DateTime dateTime)
          Formats the specified DateTime for the UTC timezone using the specified pattern.
static DateTime getDateTime(int year, int month, int day, TimeZone tz)
          Returns the moment in time for noon on the specific year, month, and day in the specified timezone.
static DateTime getDateTimeLocal(int year, int month, int day)
          Returns the moment in time for noon on the specific year, month, and day in the VM's local timezone.
static DateTime getDateTimeUTC(int year, int month, int day)
          Returns the moment in time for noon on the specific year, month, and day in the UTC timezone.
static DayOfWeek getDayOfWeek(int year, int month, int day)
           
static int getLastDayOfMonth(int year, int month)
          Returns the last day of the specified month in the specified year.
static DateTime getNow()
          Returns a DateTime that represents now (the current moment in time) as reported by getTime().
static PlainDate getPlainDate(DateTime dateTime, TimeZone tz)
          Returns the specified moment in time as a PlainDate interpreted in the specified timezone.
static PlainDate getPlainDateLocal(DateTime dateTime)
          Returns the specified moment in time as a PlainDate interpreted in the local VM timezone.
static PlainDate getPlainDateUTC(DateTime dateTime)
          Returns the specified moment in time as a PlainDate interpreted in the UTC timezone.
static long getTime()
          This method returns the number of milliseconds since Jan 1, 1970 as reported by the current DateTools.TimeSource.
static DateTools.TimeSource getTimeSource()
          Used to retrieve the DateTools.TimeSource that getTime() is currently using.
static DateTime getToday(TimeZone tz)
          Returns a DateTime that represents noon today in the specified timezone for the date/time reported by getTime().
static DateTime getTodayLocal()
          Returns a DateTime that represents noon today in the VM's timezone for the date/time reported by getTime().
static DateTime getTodayUTC()
          Returns a DateTime that represents noon today in the UTC timezone for the date/time reported by getTime().
static DateTime getTomorrow(TimeZone tz)
          Returns a DateTime that represents noon tomorrow in the specified timezone for the date/time reported by getTime().
static DateTime getTomorrowLocal()
          Returns a DateTime that represents noon tomorrow in the VM's timezone for the date/time reported by getTime().
static DateTime getTomorrowUTC()
          Returns a DateTime that represents noon tomorrow in the UTC timezone for the date/time reported by getTime().
static DateTime getYesterday(TimeZone tz)
          Returns a DateTime that represents noon yesterday in the specified timezone for the date/time reported by getTime().
static DateTime getYesterdayLocal()
          Returns a DateTime that represents noon yesterday in the VM's timezone for the date/time reported by getTime().
static DateTime getYesterdayUTC()
          Returns a DateTime that represents noon yesterday in the UTC timezone for the date/time reported by getTime().
static boolean isValidDate(int year, int month, int day)
          Returns true if the specified year, month, and day are a valid combination on the Gregorian calendar.
static DateTime parse(String dateTimeStr, TimeZone tz)
          Attempts to interpret the string passed in as a DateTime, defaulting to the specified timezone if necessary.
static DateTime parseLocal(String dateTimeStr)
          Returns a DateTime interpreted by parsing the supplied String, defaulting to the VM's timezone if necessary.
static PlainDate parsePlainDate(String dateStr)
          Attempts to interpret the string passed in as a PlainDate.
static PlainDate parsePlainDateIgnoreEmpty(String dateStr)
          Returns a PlainDate parsed from the specified dateStr or null if dateStr is empty.
static DateTime parseUTC(String dateTimeStr)
          Returns a DateTime interpreted by parsing the supplied String, defaulting to the UTC timezone if necessary.
static void setTimeSource(DateTools.TimeSource newTimeSource)
          Used to change the DateTools.TimeSource that getTime() uses.
static PlainDate subtractDaysUntil(PlainDate startDate, DayOfWeek targetDayOfWeek)
          Subtracts days (as needed) to roll the specified startDate backward until the specified targetDayOfWeek is matched.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

MS_PER_SECOND

public static final long MS_PER_SECOND
Number of milliseconds in a second (1,000).

See Also:
Constant Field Values

MS_PER_MINUTE

public static final long MS_PER_MINUTE
Typical number of milliseconds in a minute (60,000). Watch out for leap seconds which occur once in a while, and when they do, there are 61 seconds in a minute (and more rarely 59 seconds in a minute) so the value of this constant would technically be wrong. See time information for explanations of timezones, daylight saving time, leap years, leap seconds, and more.

See Also:
Constant Field Values

MS_PER_HOUR

public static final long MS_PER_HOUR
Typical number of milliseconds in an hour (3,600,000). Watch out for leap seconds which occur once in a while, and when they do, there are 61 seconds in a minute (and more rarely 59 seconds in a minute) so the value of this constant would technically be wrong. See time information for explanations of timezones, daylight saving time, leap years, leap seconds, and more.

See Also:
Constant Field Values

MS_PER_DAY

public static final long MS_PER_DAY
Typical number of milliseconds in a day (86,400,000). In a timezone that is switching on or off Daylight Saving Time, the day might only be 23 hours long, might be 25 hours long, or in some locations another odd amount (if and when a timezone goes on and off DST varies from year to year, see the United States DST history for example). Also, watch out for leap seconds which occur once in a while, and when they do, there are 61 seconds in a minute (and more rarely 59 seconds in a minute) so the value of this constant would technically be wrong. See time information for explanations of timezones, daylight saving time, leap years, leap seconds, and more.

See Also:
Constant Field Values

MS_PER_WEEK

public static final long MS_PER_WEEK
Typical number of milliseconds in a week (604,800,000). In a timezone that is switching on or off Daylight Saving Time, the day might only be 23 hours long, might be 25 hours long, or in some locations another odd amount (if and when a timezone goes on and off DST varies from year to year, see the United States DST history for example). Also, watch out for leap seconds which occur once in a while, and when they do, there are 61 seconds in a minute (and more rarely 59 seconds in a minute) so the value of this constant would technically be wrong. See time information for explanations of timezones, daylight saving time, leap years, leap seconds, and more.

See Also:
Constant Field Values

DEFAULT_TIME_SOURCE

public static final DateTools.TimeSource DEFAULT_TIME_SOURCE
This implementation of DateTools.TimeSource simply returns the time from the OS by using System.currentTimeMillis(). Passing null to setTimeSource(com.programix.time.DateTools.TimeSource) has the same effect as using this class.

Method Detail

getTime

public static long getTime()
This method returns the number of milliseconds since Jan 1, 1970 as reported by the current DateTools.TimeSource. The source of this long may or may not be from System.currentTimeMillis(). If no one has called setTimeSource(TimeSource), then the familiar System.currentTimeMillis() is used by default.

There are some other similar methods to also look at: getNow(), getToday(TimeZone), getTodayLocal(), and getTodayUTC().

See Also:
getTimeSource(), setTimeSource(TimeSource), getNow(), getToday(TimeZone), getTodayLocal(), getTodayUTC()

setTimeSource

public static void setTimeSource(DateTools.TimeSource newTimeSource)
Used to change the DateTools.TimeSource that getTime() uses. If null is passed in, then DEFAULT_TIME_SOURCE is automatically substituted.

See Also:
getTimeSource(), getTime()

getTimeSource

public static DateTools.TimeSource getTimeSource()
Used to retrieve the DateTools.TimeSource that getTime() is currently using. There is always a current DateTools.TimeSource (null is never returned).

See Also:
setTimeSource(TimeSource), getTime()

parse

public static DateTime parse(String dateTimeStr,
                             TimeZone tz)
                      throws DateTimeException
Attempts to interpret the string passed in as a DateTime, defaulting to the specified timezone if necessary. This method assumes that the specified timezone should be used to interpret the time if (and only if) no understandable timezone information is present in the supplied String.

Ideal Format:

 yyyy-mm-dd hh:mm:ss.fff
 yyyy/mm/dd hh:mm:ss.fff
 yyyy.mm.dd hh:mm:ss.fff
 
(or many subsets going to something less than milliseconds).

Also accepted is the format commonly used in the USA:

 mm-dd-yyyy hh:mm:ss.fff
 mm/dd/yyyy hh:mm:ss.fff
 mm.dd.yyyy hh:mm:ss.fff
 
(or many subsets going to something less than milliseconds).

Examples of source strings and the date/time that they imply:

Source (String) Result (DateTime) Comments
"2005-02-14 15:20:45.101" 2005-02-14 15:20:45.101 Ideal format
"20050214 152045101" 2005-02-14 15:20:45.101 No delimiters
"20050214152045101" 2005-02-14 15:20:45.101 Not even a date to time separator
"2005-02-14 15:20:45.10" 2005-02-14 15:20:45.100 Fractional seconds to hundredths, trailing zero assumed
"2005021415204510" 2005-02-14 15:20:45.100 Fractional seconds to hundredths, trailing zero assumed
"2005-02-14 15:20:45.1" 2005-02-14 15:20:45.100 Fractional seconds to tenths, trailing zeros assumed
"200502141520451" 2005-02-14 15:20:45.100 Fractional seconds to tenths, trailing zeros assumed
"2005-02-14 15:20:45.00" 2005-02-14 15:20:45.000 Fractional seconds to hundredths, trailing zero assumed
"2005-02-14 15:20:45.0" 2005-02-14 15:20:45.000 Fractional seconds to tenths, trailing zeros assumed
"2005-02-14 15:20:45" 2005-02-14 15:20:45.500 Defaults to middle of second (500 ms)
"2005-02-14 15:20" 2005-02-14 15:20:30.000 Defaults to middle of minute (30 sec)
"2005-02-14 15" 2005-02-14 15:30:00.000 Defaults to middle of hour (30 min)
"2005-02-14" 2005-02-14 12:00:00.000 Defaults to middle of day (noon)
"2005/02/14" 2005-02-14 12:00:00.000 Slash date delimiter
"2005.02.14" 2005-02-14 12:00:00.000 Dot date delimiter
"2005#02#14" 2005-02-14 12:00:00.000 Crazy date delimiter
"20050214" 2005-02-14 12:00:00.000 No date delimiter
"2005/5/6" 2005-05-06 12:00:00.000 Slash with single digits
"2005-5-6" 2005-05-06 12:00:00.000 Dash with single digits
"2005.5.6" 2005-05-06 12:00:00.000 Dot with single digits
"2005^5^6" 2005-05-06 12:00:00.000 Crazy with single digits
"02-14" 2006-02-14 12:00:00.000 Default to current year (2006)
"02/14" 2006-02-14 12:00:00.000 Default to current year (2006)
"02.14" 2006-02-14 12:00:00.000 Default to current year (2006)
"0214" 2006-02-14 12:00:00.000 Default to current year (2006)
"2.14" 2006-02-14 12:00:00.000 Default to current year (2006)
"0405" 2006-04-05 12:00:00.000 Default to current year (2006)
"4/5" 2006-04-05 12:00:00.000 Default to current year (2006)
"02-14-2005 15:20:45.101" 2005-02-14 15:20:45.101 MDY (USA) format
"02142005 152045101" 2005-02-14 15:20:45.101 MDY (USA) format, no delimiters
"02142005152045101" 2005-02-14 15:20:45.101 MDY (USA) format, no delimiters
"02/14/2005" 2005-02-14 12:00:00.000 MDY (USA) with slash date delimiter
"02.14.2005" 2005-02-14 12:00:00.000 MDY (USA) with dot date delimiter
"02142005" 2005-02-14 12:00:00.000 MDY (USA) with no delimiter
"5/6/2005" 2005-05-06 12:00:00.000 MDY (USA) with slash with single digits
"5-6-2005" 2005-05-06 12:00:00.000 MDY (USA) with dash with single digits
"5.6.2005" 2005-05-06 12:00:00.000 MDY (USA) with dot with single digits

NOTE: Currently no support for a timezone in the supplied string is present. This will change in a future release.

Parameters:
dateTimeStr - source to parse
tz - TimeZone to use as the default if necessary.
Returns:
the resulting time
Throws:
DateTimeException - if the specified string can not be successfully interpreted as a point in time. Note that DateTimeException is a RuntimeException so it does not have to be explicitly caught.

parseLocal

public static DateTime parseLocal(String dateTimeStr)
                           throws DateTimeException
Returns a DateTime interpreted by parsing the supplied String, defaulting to the VM's timezone if necessary. See parse(String, TimeZone) for full details on parsing. This method assumes the local VM's timezone should be used to interpret the time if (and only if) no understandable timezone information is present in the supplied String. The local timezone is where the the Java VM is running—be careful when two Java VMs are communicating and each is in a different timezone.

Throws:
DateTimeException

parseUTC

public static DateTime parseUTC(String dateTimeStr)
                         throws DateTimeException
Returns a DateTime interpreted by parsing the supplied String, defaulting to the UTC timezone if necessary. See parse(String, TimeZone) for full details on parsing. This method assumes the UTC timezone should be used to interpret the time if (and only if) no understandable timezone information is present in the supplied String.

Throws:
DateTimeException

format

public static String format(DateTimeFormat dtf,
                            DateTime dateTime,
                            TimeZone tz)
Formats the specified DateTime for the specified timezone.


formatLocal

public static String formatLocal(DateTimeFormat dtf,
                                 DateTime dateTime)
Formats the specified DateTime for the VM's timezone.


formatUTC

public static String formatUTC(DateTimeFormat dtf,
                               DateTime dateTime)
Formats the specified DateTime for the UTC timezone.


format

public static String format(String formatPattern,
                            DateTime dateTime,
                            TimeZone tz)
                     throws DateTimeException
Formats the specified DateTime for the specified timezone using the specified pattern.

NOTE: This method is significantly less efficient than format(DateTimeFormat, DateTime, TimeZone), so use this other format method whenever possible.

The formatPattern is as defined by SimpleDateFormat (DateTimeException is thrown if this format string is considered invalid by SimpleDateFormat).

Throws:
DateTimeException

formatLocal

public static String formatLocal(String formatPattern,
                                 DateTime dateTime)
                          throws DateTimeException
Formats the specified DateTime for the VM's timezone using the specified pattern.

NOTE: This method is significantly less efficient than formatLocal(DateTimeFormat, DateTime), so use this other format method whenever possible.

The formatPattern is as defined by SimpleDateFormat (DateTimeException is thrown if this format string is considered invalid by SimpleDateFormat).

Throws:
DateTimeException

formatUTC

public static String formatUTC(String formatPattern,
                               DateTime dateTime)
                        throws DateTimeException
Formats the specified DateTime for the UTC timezone using the specified pattern.

NOTE: This method is significantly less efficient than formatUTC(DateTimeFormat, DateTime), so use this other format method whenever possible.

The formatPattern is as defined by SimpleDateFormat (DateTimeException is thrown if this format string is considered invalid by SimpleDateFormat).

Throws:
DateTimeException

format

public static String format(DateTime dateTime,
                            TimeZone tz)
Formats the specified DateTime for the specified timezone. Format of result is: yyyy-mm-dd hh:mm:ss.fff


formatLocal

public static String formatLocal(DateTime dateTime)
Formats the specified DateTime for the VM's timezone. Format of result is: yyyy-mm-dd hh:mm:ss.fff


formatUTC

public static String formatUTC(DateTime dateTime)
Formats the specified DateTime for the UTC timezone. Format of result is: yyyy-mm-dd hh:mm:ss.fff


getNow

public static DateTime getNow()
Returns a DateTime that represents now (the current moment in time) as reported by getTime(). This result includes year, month, day, hour, minute, second, millisecond detail.


getToday

public static DateTime getToday(TimeZone tz)
Returns a DateTime that represents noon today in the specified timezone for the date/time reported by getTime(). This result includes the year, month, and day with the hour set to 12 and the minutes, seconds, and milliseconds all set to zero.


getTodayLocal

public static DateTime getTodayLocal()
Returns a DateTime that represents noon today in the VM's timezone for the date/time reported by getTime(). This result includes the year, month, and day with the hour set to 12 and the minutes, seconds, and milliseconds all set to zero.


getTodayUTC

public static DateTime getTodayUTC()
Returns a DateTime that represents noon today in the UTC timezone for the date/time reported by getTime(). This result includes the year, month, and day with the hour set to 12 and the minutes, seconds, and milliseconds all set to zero.


getYesterday

public static DateTime getYesterday(TimeZone tz)
Returns a DateTime that represents noon yesterday in the specified timezone for the date/time reported by getTime(). This result includes the year, month, and day with the hour set to 12 and the minutes, seconds, and milliseconds all set to zero.


getYesterdayLocal

public static DateTime getYesterdayLocal()
Returns a DateTime that represents noon yesterday in the VM's timezone for the date/time reported by getTime(). This result includes the year, month, and day with the hour set to 12 and the minutes, seconds, and milliseconds all set to zero.


getYesterdayUTC

public static DateTime getYesterdayUTC()
Returns a DateTime that represents noon yesterday in the UTC timezone for the date/time reported by getTime(). This result includes the year, month, and day with the hour set to 12 and the minutes, seconds, and milliseconds all set to zero.


getTomorrow

public static DateTime getTomorrow(TimeZone tz)
Returns a DateTime that represents noon tomorrow in the specified timezone for the date/time reported by getTime(). This result includes the year, month, and day with the hour set to 12 and the minutes, seconds, and milliseconds all set to zero.


getTomorrowLocal

public static DateTime getTomorrowLocal()
Returns a DateTime that represents noon tomorrow in the VM's timezone for the date/time reported by getTime(). This result includes the year, month, and day with the hour set to 12 and the minutes, seconds, and milliseconds all set to zero.


getTomorrowUTC

public static DateTime getTomorrowUTC()
Returns a DateTime that represents noon tomorrow in the UTC timezone for the date/time reported by getTime(). This result includes the year, month, and day with the hour set to 12 and the minutes, seconds, and milliseconds all set to zero.


addMilliseconds

public static DateTime addMilliseconds(DateTime startTime,
                                       int numberOfMilliseconds)
Returns a new DateTime shifted by the specified number of milliseconds. A negative numberOfMilliseconds goes back in time, a positive number goes forward in time. Timezones, daylight saving time, leap years, and leap seconds have no effect on the calculations done in this method. See time information for explanations of timezones, daylight saving time, leap years, leap seconds, and more.


addSeconds

public static DateTime addSeconds(DateTime startTime,
                                  int numberOfSeconds)
Returns a new DateTime shifted by the specified number of seconds. A negative numberOfSeconds goes back in time, a positive number goes forward in time. This method always uses MS_PER_SECOND (1000) for the number of milliseconds in one second. Timezones, daylight saving time, leap years, and leap seconds have no effect on this method. See time information for explanations of timezones, daylight saving time, leap years, leap seconds, and more.


addMinutes

public static DateTime addMinutes(DateTime startTime,
                                  int numberOfMinutes)
Returns a new DateTime shifted by the specified number of minutes. A negative numberOfMinutes goes back in time, a positive number goes forward in time. This method always uses MS_PER_MINUTE (60,000) for the number of milliseconds in one minute (which is not correct for the rare minutes that are not exactly 60 seconds long because of leap seconds). Timezones, daylight saving time, leap years, and leap seconds have no effect on this method. See time information for explanations of timezones, daylight saving time, leap years, leap seconds, and more.


addHours

public static DateTime addHours(DateTime startTime,
                                int numberOfHours)
Returns a new DateTime shifted by the specified number of hours. A negative numberOfHours goes back in time, a positive number goes forward in time. This method always uses MS_PER_HOUR (3,600,000) for the number of milliseconds in one hour (which is not correct for the rare hours that are not exactly 3,600 seconds long because of leap seconds). Timezones, daylight saving time, leap years, and leap seconds have no effect on this method. See time information for explanations of timezones, daylight saving time, leap years, leap seconds, and more.


addDays

public static DateTime addDays(DateTime startTime,
                               int numberOfDays)

addDays

public static DateTime addDays(DateTime startTime,
                               int numberOfDays,
                               TimeZone tz)

addDaysLocal

public static DateTime addDaysLocal(DateTime startTime,
                                    int numberOfDays)

addDaysUTC

public static DateTime addDaysUTC(DateTime startTime,
                                  int numberOfDays)

isValidDate

public static boolean isValidDate(int year,
                                  int month,
                                  int day)
Returns true if the specified year, month, and day are a valid combination on the Gregorian calendar.

Example Results
(year, month, day) Valid?Comment
(2006, 1, 1)true
(2006, 1, 31)true
(2006, 1, 32)false There are only 31 days in January
(2006, 2, 1)true
(2006, 2, 28)true
(2006, 2, 29)false Feb2006 is not a leap year
(2008, 2, 29)true February 29 is fine for 2008 (leap year)
(2006, 4, 30)true
(2006, 4, 31)false Only 30 days in April
(1896, 2, 29)true Leap year (divisible by 4)
(1900, 2, 29)false Not a leap year (divisible by 100)
(1904, 2, 29)true Leap year (divisible by 4)
(1996, 2, 29)true Leap year (divisible by 4)
(2000, 2, 29)true Leap year (divisible by 400)
(2004, 2, 29)true Leap year (divisible by 4)
(2096 2, 29)true Leap year (divisible by 4)
(2100, 2, 29)false Not a leap year (divisible by 100)
(1582, 10, 4)true Last day of Julian calendar (default switchover to the Gregorian calendar in Java) *
(1582, 10, 5)false Oct 5-14 do not exist in 1582 on the Gregorian calendar *
(1582, 10, 14)false Oct 5-14 do not exist in 1582 on the Gregorian calendar *
(1582, 10, 15)true Beginning of the Gregorian calendar *

* Note that the default Gregorian switchover is October 1582 for Java. This setting may be changed VM-wide and would change the results above. For example, a switchover to the Gregorian calendar took place in many countries in September 1752.

Parameters:
year - the four digit year, for example 2006.
month - the month number, from the set [1..12].
day - the day of the month, from the set [1..31].

getLastDayOfMonth

public static int getLastDayOfMonth(int year,
                                    int month)
Returns the last day of the specified month in the specified year.

Parameters:
year - the four digit year, for example 2006.
month - the month number, from the set [1..12].
Returns:
the last day of the month, from the set [1..31].

getDayOfWeek

public static DayOfWeek getDayOfWeek(int year,
                                     int month,
                                     int day)

addDays

public static PlainDate addDays(PlainDate startDate,
                                int numberOfDays)
Adds the specified number of days to the specified startDate. If the numberOfDays passed in is zero, then this method quickly and efficiently returns startDate as the result.

Parameters:
startDate - the point to start from
numberOfDays - the number of days to add (this can be a negative number to go backwards in time).
Returns:
a new PlainDate. If the numberOfDays is zero, then the original startDate is simply returned.

addWeeks

public static PlainDate addWeeks(PlainDate startDate,
                                 int numberOfWeeks)
Adds the specified number of weeks to the specified startDate. If the numberOfWeeks passed in is zero, then this method quickly and efficiently returns startDate as the result.

Parameters:
startDate - the point to start from
numberOfWeeks - the number of weeks to add (this can be a negative number to go backwards in time).
Returns:
a new PlainDate. If the numberOfWeeks is zero, then the original startDate is simply returned.

addMonths

public static PlainDate addMonths(PlainDate startDate,
                                  int numberOfMonths)
Adds the specified number of months to the specified startDate. If the numberOfMonths passed in is zero, then this method quickly and efficiently returns startDate as the result. The resulting can date might be a bit surprising as times when different length months are involved (28, 29, 30, 31):
startDate numberOfMonths
-11 23
2006-01-15 2005-12-152006-02-15 2006-03-152006-04-15
2006-01-30 2005-12-302006-02-28 2006-03-302006-04-30
2006-01-31 2005-12-312006-02-28 2006-03-312006-04-30
2008-01-31 2007-12-312008-02-29 2008-03-312008-04-30
2006-02-28 2006-01-282006-03-28 2006-04-282006-05-28
2006-02-28 2006-01-282006-03-28 2006-04-282006-05-28
2006-03-31 2006-02-282006-04-30 2006-05-312006-06-30

Parameters:
startDate - the point to start from
numberOfMonths - the number of months to add (this can be a negative number to go backwards in time).
Returns:
a new PlainDate.

addYears

public static PlainDate addYears(PlainDate startDate,
                                 int numberOfYears)
Adds the specified number of years to the specified startDate. If the numberOfYears passed in is zero, then this method quickly and efficiently returns startDate as the result. The resulting can date might be a bit surprising as times when leap years are involved:
startDate numberOfYears
-11 234
2006-01-15 2005-01-152007-01-15 2008-01-152009-01-152010-01-15
2006-02-28 2005-02-282007-02-28 2008-02-282009-02-282010-02-28
2008-02-29 2007-02-282009-02-28 2010-02-282011-02-282012-02-29

Parameters:
startDate - the point to start from
numberOfYears - the number of years to add (this can be a negative number to go backwards in time).
Returns:
a new PlainDate. If the numberOfYears is zero, then the original startDate is simply returned.

addDaysUntil

public static PlainDate addDaysUntil(PlainDate startDate,
                                     DayOfWeek targetDayOfWeek)
Adds days (as needed) to roll the specified startDate forward until the specified targetDayOfWeek is matched. The number of days added ranges from 0 up to a maximum of 6. If the day of the week for the startDate is already the specified target day of the week, then the startDate is simply returned (no change).

To find the first Monday in September 2007 (the answer is 2007-09-03):

 PlainDate firstMondayInSeptember =
     PlainDate.create("2007-09-01").addDaysUntil(DayOfWeek.MONDAY);
 

To find the first Monday in October 2007 (the starting date 2007-10-01 is actually the answer [no days need to be added]):

 PlainDate firstMondayInOctober =
     PlainDate.create("2007-10-01").addDaysUntil(DayOfWeek.MONDAY);
 

To find the first Wednesday in a month that an arbitrary date belongs to (in this case the month is June 2007, and we start from the 18th and go back to the first and then forward—if necessary—to find Wednesday. In this case, the answer is 2007-06-06):

 PlainDate randomDayInJune = PlainDate.create("2007-06-18");
 PlainDate firstWednesdayInJune =
     randomDayInJune.getFirstDayOfCurrentMonth().addDaysUntil(
         DayOfWeek.WEDNESDAY);
 

The next example takes an arbitrary date (in this case 2007-05-08) and locates all of the occurrences of a particular day of the week (in this case Thursday) in that date's month (May 2007). The resulting dates printed are the five Thursdays that occur in May 2007: 2007-05-03, 2007-05-10, 2007-05-17, 2007-05-24, and 2007-05-31.

 PlainDate startDate = PlainDate.create("2007-05-08");
 DayOfWeek targetDayOfWeek = DayOfWeek.THURSDAY;

 PlainDate currDate =
     startDate.getFirstDayOfCurrentMonth().addDaysUntil(
         targetDayOfWeek);

 while ( currDate.getMonth() == startDate.getMonth() ) {
     System.out.println("currDate=" + currDate);
     currDate = currDate.addDays(1).addDaysUntil(targetDayOfWeek);
 }
 

Parameters:
startDate - the point to start from
targetDayOfWeek - the desired day of the week
Returns:
a new PlainDate whose day of the week matches the specified target day of the week. If the startDate's day of the week was already a match for the target, then the original startDate is simply returned.
See Also:
subtractDaysUntil(PlainDate, DayOfWeek), PlainDate.addDaysUntil(DayOfWeek)

subtractDaysUntil

public static PlainDate subtractDaysUntil(PlainDate startDate,
                                          DayOfWeek targetDayOfWeek)
Subtracts days (as needed) to roll the specified startDate backward until the specified targetDayOfWeek is matched. The number of days subtracted ranges from 0 up to a maximum of 6. If the day of the week for the startDate is already the specified target day of the week, then the startDate is simply returned (no change).

To find the last Friday in July 2007 (the answer is 2007-07-27):

 PlainDate randomDayInJuly = PlainDate.create("2007-07-04");
 PlainDate lastFridayInJuly =
     randomDayInJuly.getLastDayOfCurrentMonth().subtractDaysUntil(
         DayOfWeek.FRIDAY);
 

Parameters:
startDate - the point to start from
targetDayOfWeek - the desired day of the week
Returns:
a new PlainDate whose day of the week matches the specified target day of the week. If the startDate's day of the week was already a match for the target, then the original startDate is simply returned.
See Also:
addDaysUntil(PlainDate, DayOfWeek), PlainDate.subtractDaysUntil(DayOfWeek)

getDateTime

public static DateTime getDateTime(int year,
                                   int month,
                                   int day,
                                   TimeZone tz)
Returns the moment in time for noon on the specific year, month, and day in the specified timezone.

Parameters:
year - the four digit year, for example 2006.
month - the month number, from the set [1..12].
day - the day of the month, from the set [1..31].
tz - the timezone to use to determine the moment.

getDateTimeLocal

public static DateTime getDateTimeLocal(int year,
                                        int month,
                                        int day)
Returns the moment in time for noon on the specific year, month, and day in the VM's local timezone.

Parameters:
year - the four digit year, for example 2006.
month - the month number, from the set [1..12].
day - the day of the month, from the set [1..31].

getDateTimeUTC

public static DateTime getDateTimeUTC(int year,
                                      int month,
                                      int day)
Returns the moment in time for noon on the specific year, month, and day in the UTC timezone.

Parameters:
year - the four digit year, for example 2006.
month - the month number, from the set [1..12].
day - the day of the month, from the set [1..31].

getPlainDate

public static PlainDate getPlainDate(DateTime dateTime,
                                     TimeZone tz)
Returns the specified moment in time as a PlainDate interpreted in the specified timezone.

Parameters:
dateTime - the moment in time used to determine the year/month/day.
tz - the timezone to use to determine the year/month/day.

getPlainDateLocal

public static PlainDate getPlainDateLocal(DateTime dateTime)
Returns the specified moment in time as a PlainDate interpreted in the local VM timezone.

Parameters:
dateTime - the moment in time used to determine the year/month/day.

getPlainDateUTC

public static PlainDate getPlainDateUTC(DateTime dateTime)
Returns the specified moment in time as a PlainDate interpreted in the UTC timezone.

Parameters:
dateTime - the moment in time used to determine the year/month/day.

parsePlainDate

public static PlainDate parsePlainDate(String dateStr)
                                throws PlainDateException
Attempts to interpret the string passed in as a PlainDate.

Ideal Format:

 yyyy-mm-dd
 yyyy/mm/dd
 yyyy.mm.dd
 yyyymmdd
 

Also accepted is the format commonly used in the USA:

 mm-dd-yyyy
 mm/dd/yyyy
 mm.dd.yyyy
 mmddyyyy
 

Examples of source strings and the date that they imply:

Source (String) Result (PlainDate) Comments
"2005-02-14" 2005-02-14 Ideal format
"20050214" 2005-02-14 No delimiters
"2005/02/14" 2005-02-14 Slash date delimiter
"2005.02.14" 2005-02-14 Dot date delimiter
"2005#02#14" 2005-02-14 Crazy date delimiter
"2005/5/6" 2005-05-06 Slash with single digits
"2005-5-6" 2005-05-06 Dash with single digits
"2005.5.6" 2005-05-06 Dot with single digits
"2005^5^6" 2005-05-06 Crazy with single digits
"02-14" 2006-02-14 Default to current year (2006)
"02/14" 2006-02-14 Default to current year (2006)
"02.14" 2006-02-14 Default to current year (2006)
"0214" 2006-02-14 Default to current year (2006)
"2.14" 2006-02-14 Default to current year (2006)
"0405" 2006-04-05 Default to current year (2006)
"4/5" 2006-04-05 Default to current year (2006)
"02-14-2005" 2005-02-14 MDY (USA) format
"02142005" 2005-02-14 MDY (USA) format, no delimiters
"02/14/2005" 2005-02-14 MDY (USA) with slash date delimiter
"02.14.2005" 2005-02-14 MDY (USA) with dot date delimiter
"5/6/2005" 2005-05-06 MDY (USA) with slash with single digits
"5-6-2005" 2005-05-06 MDY (USA) with dash with single digits
"5.6.2005" 2005-05-06 MDY (USA) with dot with single digits

Parameters:
dateStr - source to parse
Returns:
the resulting date
Throws:
PlainDateException - if the specified string can not be successfully interpreted as date. Note that PlainDateException is a RuntimeException so it does not have to be explicitly caught.

parsePlainDateIgnoreEmpty

public static PlainDate parsePlainDateIgnoreEmpty(String dateStr)
                                           throws PlainDateException
Returns a PlainDate parsed from the specified dateStr or null if dateStr is empty. That is, if StringTools.isEmpty(String) deems dateStr to be empty (null, zero-length string, or all whitespace), then null is returned. If dateStr is not "empty" then the parsing proceeds just as defined by parsePlainDate(String).

Parameters:
dateStr - the date to parse. It is OK to pass in null or an empty String in.
Returns:
the parsed date, or null if the passed String is "empty".
Throws:
PlainDateException - if the passed dateStr is not empty and does evaluate to a valid date.

calculateDayDifference

public static double calculateDayDifference(DateTime startTime,
                                            DateTime endTime)
Calculated the number of days from the startTime to the endTime. The number returned is a double to account for fractional parts of a day. The answer is a positive number if the endTime comes after the startTime. The answer is a negative number if the endTime comes before the startTime. The calculation uses MS_PER_DAY and therefore assumes that every day contains the same number of hours (look at MS_PER_DAY for details on the impact of daylight saving time and all the other pesky).

Parameters:
startTime - the time to subtract (subtrahend).
endTime - the time to subtract from (minuend).
Returns:
the number of days from startTime to endTime in fractional days. If either the startTime or the endTime (or both) is null, then Double.POSITIVE_INFINITY is returned.

ProgramixGenericLib v5.0.1

Copyright © 2001-2009 Programix Incorporated. All rights reserved. ProgramixGenericLib is free and is OSI Certified Open Source Software under the BSD license.