Version 4.10.0

hirondelle.web4j.model
Class DateTime

Object
  extended by hirondelle.web4j.model.DateTime
All Implemented Interfaces:
Serializable, Comparable<DateTime>

public final class DateTime
extends Object
implements Comparable<DateTime>, Serializable

Building block class for an immutable date-time, with no time zone.

This class is provided as an alternative to java.util.Date. You're strongly encouraged to use this class in your WEB4J applications, but you can still use java.util.Date if you wish.

This class can hold :

Examples
Justification For This Class
Dates and Times In General
The Approach Used By This Class
Two Sets Of Operations
Parsing DateTime - Accepted Formats
Mini-Language for Formatting
Interaction with TimeSource
Passing DateTime Objects to the Database

Examples

Some quick examples of using this class :
  DateTime dateAndTime = new DateTime("2010-01-19 23:59:59");
  //highest precision is nanosecond, not millisecond:
  DateTime dateAndTime = new DateTime("2010-01-19 23:59:59.123456789");

  DateTime dateOnly = new DateTime("2010-01-19");
  DateTime timeOnly = new DateTime("23:59:59");

  DateTime dateOnly = DateTime.forDateOnly(2010,01,19);
  DateTime timeOnly = DateTime.forTimeOnly(23,59,59,0);

  DateTime dt = new DateTime("2010-01-15 13:59:15");
  boolean leap = dt.isLeapYear(); //false
  dt.getNumDaysInMonth(); //31
  dt.getStartOfMonth(); //2010-01-01, 00:00:00
  dt.getEndOfDay(); //2010-01-15, 23:59:59
  dt.format("YYYY-MM-DD"); //formats as '2010-01-15'
  dt.plusDays(30); //30 days after Jan 15
  dt.numDaysFrom(someDate); //returns an int
  dueDate.lt(someDate); //less-than
  dueDate.lteq(someDate); //less-than-or-equal-to

  //ActionImpl.getTimeZone() is readily available in most Actions
  DateTime.now(getTimeZone());
  DateTime.today(getTimeZone());
  DateTime fromMilliseconds = DateTime.forInstant(31313121L, getTimeZone());
  birthday.isInFuture(getTimeZone());
 

Justification For This Class

The fundamental reasons why this class exists are :

There are 2 distinct mental models for date-times, and they don't play well together :

The problem is that java.util.Date uses only the timeline style, while most users, most of the time, think in terms of the other mental model - the 'everday' style. In particular, there are a large number of applications which experience problems with time zones, because the timeline model is used instead of the everday model. Such problems are often seen by end users as serious bugs, because telling people the wrong date or time is often a serious issue. These problems make you look stupid.

Date Classes in the JDK are Mediocre

The JDK's classes related to dates are widely regarded as frustrating to work with, for various reasons:

Joda Time Has Drawbacks As Well

The Joda Time library is used by some programmers as an alternative to the JDK classes. Joda Time has the following drawbacks :

Dates and Times in General

Civil Timekeeping Is Complex

Civil timekeeping is a byzantine hodge-podge of arcane and arbitrary rules. Consider the following :

How Databases Treat Dates

Most databases model dates and times using the Gregorian Calendar in an aggressively simplified form, in which :

The final point requires elaboration. Some may doubt its veracity, since they have seen date-time information "change time zone" when retrieved from a database. But this sort of change is usually applied using logic which is external to the data stored in the particular column.

For example, the following items might be used in the calculation of a time zone difference :

(Note as well what's missing from the above list: your own application's logic, and the user's time zone preference.)

When an end user sees such changes to a date-time, all they will say to you is "Why did you change it? That's not what I entered" - and this is a completely valid question. Why did you change it? Because you're using the timeline model instead of the everyday model. Perhaps you're using a inappropriate abstraction for what the user really wants.

The Approach Used By This Class

This class takes the following design approach :

Even though the above list may appear restrictive, it's very likely true that DateTime can handle the dates and times you're currently storing in your database.

Two Sets Of Operations

This class allows for 2 sets of operations: a few "basic" operations, and many "computational" ones.

Basic operations model the date-time as a simple, dumb String, with absolutely no parsing or substructure. This will always allow your application to reflect exactly what is in a ResultSet, with absolutely no modification for time zone, locale, or for anything else.

This is meant as a back-up, to ensure that your application will always be able to, at the very least, display a date-time exactly as it appears in your ResultSet from the database. This style is particularly useful for handling invalid dates such as 2009-00-00, which can in fact be stored by some databases (MySQL, for example). It can also be used to handle unusual items, such as MySQL's TIME datatype.

The basic operations are represented by DateTime(String), toString(), and getRawDateString().

Computational operations allow for calculations and formatting. If a computational operation is performed by this class (for example, if the caller asks for the month), then any underlying date-time String must be parseable by this class into its components - year, month, day, and so on. Computational operations require such parsing, while the basic operations do not. Almost all methods in this class are categorized as computational operations.

Parsing DateTime - Accepted Formats

The DateTime(String) constructor accepts a String representation of a date-time. The format of the String can take a number of forms. When retrieving date-times from a database, the majority of cases will have little problem in conforming to these formats. If necessary, your SQL statements can almost always use database formatting functions to generate a String whose format conforms to one of the many formats accepted by the DateTime(String) constructor.

Mini-Language for Formatting

This class defines a simple mini-language for formatting a DateTime, used by the various format methods.

The following table defines the symbols used by this mini-language, and the corresponding text they would generate given the date:

1958-04-09 Wednesday, 03:05:06.123456789 AM
in an English Locale. (Items related to date are in upper case, and items related to time are in lower case.)

FormatOutput DescriptionNeeds Locale?
YYYY 1958 Year...
YY 58 Year without century...
M 4 Month 1..12...
MM 04 Month 01..12...
MMM Apr Month Jan..DecYes
MMMM April Month January..DecemberYes
DD 09 Day 01..31...
D 9 Day 1..31...
WWWW Wednesday Weekday Sunday..SaturdayYes
WWW Wed Weekday Sun..SatYes
hh 03 Hour 01..23...
h 3 Hour 1..23...
hh12 03 Hour 01..12...
h12 3 Hour 1..12...
a AM AM/PM IndicatorYes
mm 05 Minutes 01..59...
m 5 Minutes 1..59...
ss 06 Seconds 01..59...
s 6 Seconds 1..59...
f 1 Fractional Seconds, 1 decimal...
ff 12 Fractional Seconds, 2 decimals...
fff 123 Fractional Seconds, 3 decimals...
ffff 1234 Fractional Seconds, 4 decimals...
fffff 12345 Fractional Seconds, 5 decimals...
ffffff 123456 Fractional Seconds, 6 decimals...
fffffff 1234567 Fractional Seconds, 7 decimals...
ffffffff 12345678 Fractional Seconds, 8 decimals...
fffffffff 123456789 Fractional Seconds, 9 decimals...
| (no example) Escape character...

As indicated above, some of these symbols can only be used with an accompanying Locale. In general, if the output is text, not a number, then a Locale will be needed. For example, 'September' is localizable text, while '09' is a numeric representation, which doesn't require a Locale. Thus, the symbol 'MM' can be used without a Locale, while 'MMMM' and 'MMM' both require a Locale, since they generate text, not a number.

The fractional seconds 'f' does not perform any rounding.

The escape character '|' allows you to insert arbitrary text. The escape character always appears in pairs; these pairs define a range of characters over which the text will not be interpreted using the special format symbols defined above.

Examples :

FormatOutput
YYYY-MM-DD hh:mm:ss.fffffffff a 1958-04-09 03:05:06.123456789 AM
YYYY-MM-DD hh:mm:ss.fff a 1958-04-09 03:05:06.123 AM
YYYY-MM-DD 1958-04-09
hh:mm:ss.fffffffff 03:05:06.123456789
hh:mm:ss 03:05:06
YYYY-M-D h:m:s 1958-4-9 3:5:6
WWWW, MMMM D, YYYY Wednesday, April 9, 1958
WWWW, MMMM D, YYYY |at| D a Wednesday, April 9, 1958 at 3 AM

In the last example, the escape characters are needed only because 'a', the formating symbol for am/pm, appears in the text.

Interaction with TimeSource

The methods of this class related to the current date interact with your configured implementation of TimeSource. That is, now(TimeZone) and today(TimeZone) will return values derived from TimeSource. Thus, callers of this class automatically use any 'fake' system clock that you may want to define.

Passing DateTime Objects to the Database

When a DateTime is passed as a parameter to an SQL statement, the DateTime is formatted into a String of a form accepted by the database. There are two mechanisms to accomplish this

See Also:
Serialized Form

Nested Class Summary
static class DateTime.DayOverflow
          Policy for treating 'day-of-the-month overflow' conditions encountered during some date calculations.
static class DateTime.Unit
          The seven parts of a DateTime object.
 
Constructor Summary
DateTime(Integer aYear, Integer aMonth, Integer aDay, Integer aHour, Integer aMinute, Integer aSecond, Integer aNanoseconds)
          Constructor taking each time unit explicitly.
DateTime(String aDateTime)
          Constructor taking a date-time as a String.
 
Method Summary
 DateTime changeTimeZone(TimeZone aFromTimeZone, TimeZone aToTimeZone)
          Return a DateTime corresponding to a change from one TimeZone to another.
 int compareTo(DateTime aThat)
          Compare this object to another, for ordering purposes.
 boolean equals(Object aThat)
          Equals method for this object.
static DateTime forDateOnly(Integer aYear, Integer aMonth, Integer aDay)
          Factory method returns a DateTime having year-month-day only, with no time portion.
static DateTime forInstant(long aMilliseconds, TimeZone aTimeZone)
          Constructor taking a millisecond value and a TimeZone.
static DateTime forInstantNanos(long aNanoseconds, TimeZone aTimeZone)
          Constructor taking a nanosecond value and a TimeZone.
 String format(String aFormat)
          Output this DateTime as a formatted String using numbers, with no localizable text.
 String format(String aFormat, List<String> aMonths, List<String> aWeekdays, List<String> aAmPmIndicators)
          Output this DateTime as a formatted String using numbers and explicit text for months, weekdays, and AM/PM indicator.
 String format(String aFormat, Locale aLocale)
          Output this DateTime as a formatted String using numbers and/or localizable text.
static DateTime forTimeOnly(Integer aHour, Integer aMinute, Integer aSecond, Integer aNanoseconds)
          Factory method returns a DateTime having hour-minute-second-nanosecond only, with no date portion.
 Integer getDay()
          Return the Day of the Month, 1..31.
 Integer getDayOfYear()
          Return an integer in the range 1..366, representing a count of the number of days from the start of the year.
 DateTime getEndOfDay()
          Return this DateTime with the time portion coerced to '23:59:59.999999999'.
 DateTime getEndOfMonth()
          Return this DateTime with the time portion coerced to '23:59:59.999999999', and the day coerced to the end of the month.
 Integer getHour()
          Return the Hour, 0..23.
 long getMilliseconds(TimeZone aTimeZone)
          For the given time zone, return the corresponding time in milliseconds-since-epoch for this DateTime.
 Integer getMinute()
          Return the Minute, 0..59.
 Integer getModifiedJulianDayNumber()
          Return the Modified Julian Day Number.
 Integer getMonth()
          Return the Month, 1..12.
 Integer getNanoseconds()
          Return the Nanosecond, 0..999999999.
 long getNanosecondsInstant(TimeZone aTimeZone)
          For the given time zone, return the corresponding time in nanoseconds-since-epoch for this DateTime.
 int getNumDaysInMonth()
          Return the number of days in the month which holds this DateTime.
 DateTime.Unit getPrecision()
          Return the smallest non-null time unit encapsulated by this DateTime.
 String getRawDateString()
          Return the raw date-time String passed to the DateTime(String) constructor.
 Integer getSecond()
          Return the Second, 0..59.
 DateTime getStartOfDay()
          Return this DateTime with the time portion coerced to '00:00:00.000000000'.
 DateTime getStartOfMonth()
          Return this DateTime with the time portion coerced to '00:00:00.000000000', and the day coerced to 1.
 Integer getWeekDay()
          Return an index for the weekday for this DateTime.
 Integer getWeekIndex()
          Return The week index of this DateTime, taking day 1 of week 1 as Sunday, January 2, 2000.
 Integer getWeekIndex(DateTime aStartingFromDate)
          Return The week index of this DateTime with respect to a given starting DateTime.
 Integer getYear()
          Return the year, 1..9999.
 boolean gt(DateTime aThat)
          'Greater than' comparison.
 boolean gteq(DateTime aThat)
          'Greater than or equal to' comparison.
 int hashCode()
          Hash code for this object.
 boolean hasHourMinuteSecond()
          Return true only if this DateTime has a non-null values for hour, minute, and second.
 boolean hasYearMonthDay()
          Return true only if this DateTime has a non-null values for year, month, and day.
 boolean isInTheFuture(TimeZone aTimeZone)
          Return true only if this date is in the future, with respect to now(TimeZone).
 boolean isInThePast(TimeZone aTimeZone)
          Return true only if this date is in the past, with respect to now(TimeZone).
 Boolean isLeapYear()
          Returns true only if the year is a leap year.
static boolean isParseable(String aCandidateDateTime)
          Return true only if the given String follows one of the formats documented by DateTime(String).
 boolean isSameDayAs(DateTime aThat)
          Return true only if this DateTime has the same year-month-day as the given parameter.
 boolean lt(DateTime aThat)
          'Less than' comparison.
 boolean lteq(DateTime aThat)
          'Less than or equal to' comparison.
 DateTime minus(Integer aNumYears, Integer aNumMonths, Integer aNumDays, Integer aNumHours, Integer aNumMinutes, Integer aNumSeconds, Integer aNumNanoseconds, DateTime.DayOverflow aDayOverflow)
          Create a new DateTime by subtracting an interval to this one.
 DateTime minusDays(Integer aNumDays)
          Return a new DateTime by subtracting an integral number of days from this one.
static DateTime now(TimeZone aTimeZone)
          Return the current date-time.
 int numDaysFrom(DateTime aThat)
          The whole number of days between this DateTime and the given parameter.
 long numSecondsFrom(DateTime aThat)
          The number of seconds between this DateTime and the given argument.
 DateTime plus(Integer aNumYears, Integer aNumMonths, Integer aNumDays, Integer aNumHours, Integer aNumMinutes, Integer aNumSeconds, Integer aNumNanoseconds, DateTime.DayOverflow aDayOverflow)
          Create a new DateTime by adding an interval to this one.
 DateTime plusDays(Integer aNumDays)
          Return a new DateTime by adding an integral number of days to this one.
static DateTime today(TimeZone aTimeZone)
          Return the current date.
 String toString()
          Intended for debugging and logging only.
 DateTime truncate(DateTime.Unit aPrecision)
          Truncate this DateTime to the given precision.
 boolean unitsAllAbsent(DateTime.Unit... aUnits)
          Return true only if all of the given units are absent from this DateTime.
 boolean unitsAllPresent(DateTime.Unit... aUnits)
          Return true only if all of the given units are present in this DateTime.
 
Methods inherited from class Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

DateTime

public DateTime(String aDateTime)
Constructor taking a date-time as a String.

This constructor is called when WEB4J's data layer needs to translate a column in a ResultSet into a DateTime.

When this constructor is called, the underlying text can be in an absolutely arbitrary form, since it will not, initially, be parsed in any way. This policy of extreme leniency allows you to use dates in an arbitrary format, without concern over possible transformations of the date (time zone in particular), and without concerns over possibly bizarre content, such as '2005-00-00', as seen in some databases, such as MySQL.

However, the moment you attempt to call almost any method in this class, an attempt will be made to parse the given date-time string into its constituent parts. Then, if the date-time string does not match one of the example formats listed below, a RuntimeException will be thrown.

Before calling this constructor, you may wish to call isParseable(String) to explicitly test whether a given String is parseable by this class.

The full date format expected by this class is 'YYYY-MM-YY hh:mm:ss.fffffffff'. All fields except for the fraction of a second have a fixed width. In addition, various portions of this format are also accepted by this class.

All of the following dates can be parsed by this class to make a DateTime :

The range of each field is :

Note that database format functions are an option when dealing with date formats. Since your application is always in control of the SQL used to talk to the database, you can, if needed, usually use database format functions to alter the format of dates returned in a ResultSet.


DateTime

public DateTime(Integer aYear,
                Integer aMonth,
                Integer aDay,
                Integer aHour,
                Integer aMinute,
                Integer aSecond,
                Integer aNanoseconds)
Constructor taking each time unit explicitly.

Although all parameters are optional, many operations on this class require year-month-day to be present.

Parameters:
aYear - 1..9999, optional
aMonth - 1..12 , optional
aDay - 1..31, cannot exceed the number of days in the given month/year, optional
aHour - 0..23, optional
aMinute - 0..59, optional
aSecond - 0..59, optional
aNanoseconds - 0..999,999,999, optional (allows for databases that store timestamps up to nanosecond precision).
Method Detail

isParseable

public static boolean isParseable(String aCandidateDateTime)
Return true only if the given String follows one of the formats documented by DateTime(String).

If the text is not from a trusted source, then the caller may use this method to validate whether the text is in a form that's parseable by this class.


forDateOnly

public static DateTime forDateOnly(Integer aYear,
                                   Integer aMonth,
                                   Integer aDay)
Factory method returns a DateTime having year-month-day only, with no time portion.

See DateTime(Integer, Integer, Integer, Integer, Integer, Integer, Integer) for constraints on the parameters.


forTimeOnly

public static DateTime forTimeOnly(Integer aHour,
                                   Integer aMinute,
                                   Integer aSecond,
                                   Integer aNanoseconds)
Factory method returns a DateTime having hour-minute-second-nanosecond only, with no date portion.

See DateTime(Integer, Integer, Integer, Integer, Integer, Integer, Integer) for constraints on the parameters.


forInstant

public static DateTime forInstant(long aMilliseconds,
                                  TimeZone aTimeZone)
Constructor taking a millisecond value and a TimeZone. This constructor may be use to convert a java.util.Date into a DateTime.

To use nanosecond precision, please use forInstantNanos(long, TimeZone) instead.

Parameters:
aMilliseconds - must be in the range corresponding to the range of dates supported by this class (year 1..9999); corresponds to a millisecond instant on the timeline, measured from the epoch used by Date.

getMilliseconds

public long getMilliseconds(TimeZone aTimeZone)
For the given time zone, return the corresponding time in milliseconds-since-epoch for this DateTime.

This method is meant to help you convert between a DateTime and the JDK's date-time classes, which are based on the combination of a time zone and a millisecond value from the Java epoch.

Since DateTime can go to nanosecond accuracy, the return value can lose precision. The nanosecond value is truncated to milliseconds, not rounded. To retain nanosecond accuracy, please use getNanosecondsInstant(TimeZone) instead.

Requires year-month-day to be present; if not, a runtime exception is thrown.


forInstantNanos

public static DateTime forInstantNanos(long aNanoseconds,
                                       TimeZone aTimeZone)
Constructor taking a nanosecond value and a TimeZone.

To use milliseconds instead of nanoseconds, please use forInstant(long, TimeZone).

Parameters:
aNanoseconds - must be in the range corresponding to the range of dates supported by this class (year 1..9999); corresponds to a nanosecond instant on the time-line, measured from the epoch used by Date.

getNanosecondsInstant

public long getNanosecondsInstant(TimeZone aTimeZone)
For the given time zone, return the corresponding time in nanoseconds-since-epoch for this DateTime.

For conversion between a DateTime and the JDK's date-time classes, you should likely use getMilliseconds(TimeZone) instead.

Requires year-month-day to be present; if not, a runtime exception is thrown.


getRawDateString

public String getRawDateString()
Return the raw date-time String passed to the DateTime(String) constructor. Returns null if that constructor was not called. See toString() as well.


getYear

public Integer getYear()
Return the year, 1..9999.


getMonth

public Integer getMonth()
Return the Month, 1..12.


getDay

public Integer getDay()
Return the Day of the Month, 1..31.


getHour

public Integer getHour()
Return the Hour, 0..23.


getMinute

public Integer getMinute()
Return the Minute, 0..59.


getSecond

public Integer getSecond()
Return the Second, 0..59.


getNanoseconds

public Integer getNanoseconds()
Return the Nanosecond, 0..999999999.


getModifiedJulianDayNumber

public Integer getModifiedJulianDayNumber()
Return the Modified Julian Day Number.

The Modified Julian Day Number is defined by astronomers for simplifying the calculation of the number of days between 2 dates. Returns a monotonically increasing sequence number. Day 0 is November 17, 1858 00:00:00 (whose Julian Date was 2400000.5).

Using the Modified Julian Day Number instead of the Julian Date has 2 advantages:

Does not reflect any time portion, if present.

(In spite of its name, this method, like all other methods in this class, uses the proleptic Gregorian calendar - not the Julian calendar.)

Requires year-month-day to be present; if not, a runtime exception is thrown.


getWeekDay

public Integer getWeekDay()
Return an index for the weekday for this DateTime. Returns 1..7 for Sunday..Saturday.

Requires year-month-day to be present; if not, a runtime exception is thrown.


getDayOfYear

public Integer getDayOfYear()
Return an integer in the range 1..366, representing a count of the number of days from the start of the year. January 1 is counted as day 1.

Requires year-month-day to be present; if not, a runtime exception is thrown.


isLeapYear

public Boolean isLeapYear()
Returns true only if the year is a leap year.

Requires year to be present; if not, a runtime exception is thrown.


getNumDaysInMonth

public int getNumDaysInMonth()
Return the number of days in the month which holds this DateTime.

Requires year-month-day to be present; if not, a runtime exception is thrown.


getWeekIndex

public Integer getWeekIndex(DateTime aStartingFromDate)
Return The week index of this DateTime with respect to a given starting DateTime.

The single parameter to this method defines first day of week number 1. See getWeekIndex() as well.

Requires year-month-day to be present; if not, a runtime exception is thrown.


getWeekIndex

public Integer getWeekIndex()
Return The week index of this DateTime, taking day 1 of week 1 as Sunday, January 2, 2000.

See getWeekIndex(DateTime) as well, which takes an arbitrary date to define day 1 of week 1.

Requires year-month-day to be present; if not, a runtime exception is thrown.


isSameDayAs

public boolean isSameDayAs(DateTime aThat)
Return true only if this DateTime has the same year-month-day as the given parameter. Time is ignored by this method.

Requires year-month-day to be present, both for this DateTime and for aThat; if not, a runtime exception is thrown.


lt

public boolean lt(DateTime aThat)
'Less than' comparison. Return true only if this DateTime comes before the given parameter, according to compareTo(DateTime).


lteq

public boolean lteq(DateTime aThat)
'Less than or equal to' comparison. Return true only if this DateTime comes before the given parameter, according to compareTo(DateTime), or this DateTime equals the given parameter.


gt

public boolean gt(DateTime aThat)
'Greater than' comparison. Return true only if this DateTime comes after the given parameter, according to compareTo(DateTime).


gteq

public boolean gteq(DateTime aThat)
'Greater than or equal to' comparison. Return true only if this DateTime comes after the given parameter, according to compareTo(DateTime), or this DateTime equals the given parameter.


getPrecision

public DateTime.Unit getPrecision()
Return the smallest non-null time unit encapsulated by this DateTime.


truncate

public DateTime truncate(DateTime.Unit aPrecision)
Truncate this DateTime to the given precision.

The return value will have all items lower than the given precision simply set to null. In addition, the return value will not include any date-time String passed to the DateTime(String) constructor.

Parameters:
aPrecision - takes any value except DateTime.Unit.NANOSECONDS (since it makes no sense to truncate to the highest available precision).

unitsAllPresent

public boolean unitsAllPresent(DateTime.Unit... aUnits)
Return true only if all of the given units are present in this DateTime. If a unit is not included in the argument list, then no test is made for its presence or absence in this DateTime by this method.


hasYearMonthDay

public boolean hasYearMonthDay()
Return true only if this DateTime has a non-null values for year, month, and day.


hasHourMinuteSecond

public boolean hasHourMinuteSecond()
Return true only if this DateTime has a non-null values for hour, minute, and second.


unitsAllAbsent

public boolean unitsAllAbsent(DateTime.Unit... aUnits)
Return true only if all of the given units are absent from this DateTime. If a unit is not included in the argument list, then no test is made for its presence or absence in this DateTime by this method.


getStartOfDay

public DateTime getStartOfDay()
Return this DateTime with the time portion coerced to '00:00:00.000000000'.

Requires year-month-day to be present; if not, a runtime exception is thrown.


getEndOfDay

public DateTime getEndOfDay()
Return this DateTime with the time portion coerced to '23:59:59.999999999'.

Requires year-month-day to be present; if not, a runtime exception is thrown.


getStartOfMonth

public DateTime getStartOfMonth()
Return this DateTime with the time portion coerced to '00:00:00.000000000', and the day coerced to 1.

Requires year-month-day to be present; if not, a runtime exception is thrown.


getEndOfMonth

public DateTime getEndOfMonth()
Return this DateTime with the time portion coerced to '23:59:59.999999999', and the day coerced to the end of the month.

Requires year-month-day to be present; if not, a runtime exception is thrown.


plus

public DateTime plus(Integer aNumYears,
                     Integer aNumMonths,
                     Integer aNumDays,
                     Integer aNumHours,
                     Integer aNumMinutes,
                     Integer aNumSeconds,
                     Integer aNumNanoseconds,
                     DateTime.DayOverflow aDayOverflow)
Create a new DateTime by adding an interval to this one.

See plusDays(Integer) as well.

Changes are always applied by this class in order of decreasing units of time: years first, then months, and so on. After changing both the year and month, a check on the month-day combination is made before any change is made to the day. If the day exceeds the number of days in the given month/year, then (and only then) the given DateTime.DayOverflow policy applied, and the day-of-the-month is adusted accordingly.

Afterwards, the day is then changed in the usual way, followed by the remaining items (hour, minute, second, and nanosecond).

The mental model for this method is very similar to that of a car's odometer. When a limit is reach for one unit of time, then a rollover occurs for a neighbouring unit of time.

The returned value cannot come after 9999-12-13 23:59:59.

This class works with DateTime's having the following items present :

Parameters:
aNumYears - positive, required, in range 0...9999
aNumMonths - positive, required, in range 0...9999
aNumDays - positive, required, in range 0...9999
aNumHours - positive, required, in range 0...9999
aNumMinutes - positive, required, in range 0...9999
aNumSeconds - positive, required, in range 0...9999
aNumNanoseconds - positive, required, in range 0...999999999

minus

public DateTime minus(Integer aNumYears,
                      Integer aNumMonths,
                      Integer aNumDays,
                      Integer aNumHours,
                      Integer aNumMinutes,
                      Integer aNumSeconds,
                      Integer aNumNanoseconds,
                      DateTime.DayOverflow aDayOverflow)
Create a new DateTime by subtracting an interval to this one.

See minusDays(Integer) as well.

This method has nearly the same behavior as plus(Integer, Integer, Integer, Integer, Integer, Integer, Integer, DayOverflow), except that the return value cannot come before 0001-01-01 00:00:00.


plusDays

public DateTime plusDays(Integer aNumDays)
Return a new DateTime by adding an integral number of days to this one.

Requires year-month-day to be present; if not, a runtime exception is thrown.

Parameters:
aNumDays - can be either sign; if negative, then the days are subtracted.

minusDays

public DateTime minusDays(Integer aNumDays)
Return a new DateTime by subtracting an integral number of days from this one.

Requires year-month-day to be present; if not, a runtime exception is thrown.

Parameters:
aNumDays - can be either sign; if negative, then the days are added.

numDaysFrom

public int numDaysFrom(DateTime aThat)
The whole number of days between this DateTime and the given parameter.

Requires year-month-day to be present, both for this DateTime and for the aThat parameter; if not, a runtime exception is thrown.


numSecondsFrom

public long numSecondsFrom(DateTime aThat)
The number of seconds between this DateTime and the given argument.

If only time information is present in both this DateTime and aThat, then there are no restrictions on the values of the time units.

If any date information is present, in either this DateTime or aThat, then full year-month-day must be present in both; if not, then the date portion will be ignored, and only the time portion will contribute to the calculation.


format

public String format(String aFormat)
Output this DateTime as a formatted String using numbers, with no localizable text.

Example:

dt.format("YYYY-MM-DD hh:mm:ss");
would generate text of the form
2009-09-09 18:23:59

If months, weekdays, or AM/PM indicators are output as localizable text, you must use format(String, Locale).

Parameters:
aFormat - uses the formatting mini-language defined in the class comment.

format

public String format(String aFormat,
                     Locale aLocale)
Output this DateTime as a formatted String using numbers and/or localizable text.

This method is intended for alphanumeric output, such as 'Sunday, November 14, 1858 10:00 AM'.

If months and weekdays are output as numbers, you are encouraged to use format(String) instead.

Parameters:
aFormat - uses the formatting mini-language defined in the class comment.
aLocale - used to generate text for Month, Weekday and AM/PM indicator; required only by patterns which return localized text, instead of numeric forms.

format

public String format(String aFormat,
                     List<String> aMonths,
                     List<String> aWeekdays,
                     List<String> aAmPmIndicators)
Output this DateTime as a formatted String using numbers and explicit text for months, weekdays, and AM/PM indicator.

Use of this method is likely relatively rare; it should be used only if the output of format(String, Locale) is inadequate.

Parameters:
aFormat - uses the formatting mini-language defined in the class comment.
aMonths - contains text for all 12 months, starting with January; size must be 12.
aWeekdays - contains text for all 7 weekdays, starting with Sunday; size must be 7.
aAmPmIndicators - contains text for A.M and P.M. indicators (in that order); size must be 2.

now

public static DateTime now(TimeZone aTimeZone)
Return the current date-time.

Combines the configured implementation of TimeSource with the given TimeZone. The TimeZone will typically come from your implementation of TimeZoneSource.

In an Action, the current date-time date can be referenced using

DateTime.now(getTimeZone())
See ActionImpl.getTimeZone().

Only millisecond precision is possible for this method.


today

public static DateTime today(TimeZone aTimeZone)
Return the current date.

As in now(TimeZone), but truncates the time portion, leaving only year-month-day.

In an Action, today's date can be referenced using

DateTime.today(getTimeZone())
See ActionImpl.getTimeZone().


isInTheFuture

public boolean isInTheFuture(TimeZone aTimeZone)
Return true only if this date is in the future, with respect to now(TimeZone).


isInThePast

public boolean isInThePast(TimeZone aTimeZone)
Return true only if this date is in the past, with respect to now(TimeZone).


changeTimeZone

public DateTime changeTimeZone(TimeZone aFromTimeZone,
                               TimeZone aToTimeZone)
Return a DateTime corresponding to a change from one TimeZone to another.

A DateTime object has an implicit and immutable time zone. If you need to change the implicit time zone, you can use this method to do so.

Example :

TimeZone fromUK = TimeZone.getTimeZone("Europe/London");
TimeZone toIndonesia = TimeZone.getTimeZone("Asia/Jakarta");
DateTime newDt = oldDt.changeTimeZone(fromUK, toIndonesia);
    

Requires year-month-day-hour to be present; if not, a runtime exception is thrown.

Parameters:
aFromTimeZone - the implicit time zone of this object.
aToTimeZone - the implicit time zone of the DateTime returned by this method.
Returns:
aDateTime corresponding to the change of time zone implied by the 2 parameters.

compareTo

public int compareTo(DateTime aThat)
Compare this object to another, for ordering purposes.

Uses the 7 date-time elements (year..nanosecond). The Year is considered the most significant item, and the Nanosecond the least significant item. Null items are placed first in this comparison.

Specified by:
compareTo in interface Comparable<DateTime>

equals

public boolean equals(Object aThat)
Equals method for this object.

Equality is determined by the 7 date-time elements (year..nanosecond).

Overrides:
equals in class Object

hashCode

public int hashCode()
Hash code for this object.

Uses the same 7 date-time elements (year..nanosecond) as used by equals(Object).

Overrides:
hashCode in class Object

toString

public String toString()
Intended for debugging and logging only.

To format this DateTime for presentation to the user, see the various format methods.

If the DateTime(String) constructor was called, then return that String.

Otherwise, the return value is constructed from each date-time element, in a fixed format, depending on which time units are present. Example values :

In the great majority of cases, this will give reasonable output for debugging and logging statements.

In cases where a bizarre combinations of time units is present, the return value is presented in a verbose form. For example, if all time units are present except for minutes, the return value has this form:

Y:2001 M:1 D:31 h:13 m:null s:59 f:123456789

Overrides:
toString in class Object

Version 4.10.0

Copyright Hirondelle Systems. Published October 19, 2013 - User Guide - All Docs.