DateTime

Date Time Object - DateTime

Origin

Considering the limitations of tool classes, they are not always convenient to use in certain situations. Therefore, the DateTime class was born. The DateTime object fully absorbs the advantages of the Joda-Time library and provides more convenient methods, so we no longer need to import the Joda-Time library separately in development to enjoy the simple and fast processing of date and time.

Explanation

DateTime class inherited from java.util.Date class and extends it with numerous convenient methods. These methods are mostly object manifestations of the static methods of DateUtil, and using DateTime objects can completely replace the use of Date objects in development.

Usage

New Object

DateTime objects contain many constructors. The constructors support the following parameters:

  • Date
  • Calendar
  • String (date string, the second parameter is the date format)
  • long milliseconds

There are two ways to build objects: DateTime.of() and new DateTime():

Date date = new Date();

// New way to create
DateTime time = new DateTime(date);
Console.log(time);

// Of way to create
DateTime now = DateTime.now();
DateTime dt = DateTime.of(date);

Using Objects

DateTime has member methods corresponding to static methods in DateUtil, but because they are member methods, they can be operated with fewer parameters.

Example: Accessing date members (year, month, day, etc.)

DateTime dateTime = new DateTime("2017-01-05 12:34:23", DatePattern.NORM_DATETIME_FORMAT);

// Year, result: 2017
int year = dateTime.year();

// Season (non-season), result: Season.SPRING
Season season = dateTime.seasonEnum();

// Month, result: Month.JANUARY
Month month = dateTime.monthEnum();

// Day, result: 5
int day = dateTime.dayOfMonth();

Please refer to the API document for more member methods.

Object Mutability

DateTime objects are mutable by default (calling offset, setField, setTime methods will change themselves), but this mutability can sometimes cause many problems (for example, multiple places share DateTime objects). We can call the setMutable(false) method to make it an immutable object. In immutable mode, offset, setField methods return a new object, and setTime methods throw an exception.

DateTime dateTime = new DateTime("2017-01-05 12:34:23", DatePattern.NORM_DATETIME_FORMAT);

// By default, DateTime is a mutable object, so offset == dateTime
DateTime offset = dateTime.offset(DateField.YEAR, 0);

// Set it as an immutable object after the change, and offset != dateTime
dateTime.setMutable(false);
offset = dateTime.offset(DateField.YEAR, 0);

Formatting into Strings

Call the toString() method to return a string formatted as yyyy-MM-dd HH:mm:ss. Call toString(String format) to return a string with a specified format.

DateTime dateTime = new DateTime("2017-01-05 12:34:23", DatePattern.NORM_DATETIME_FORMAT);
// Result: 2017-01-05 12:34:23
String dateStr = dateTime.toString();

// Result: 2017/01/05