Joda-Time

Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

/*
* 将Date转换成DateTime
*/
java.util.Date juDate = new Date();
DateTime dt = new DateTime(juDate);

获取年月日

DateTime dt = new DateTime();
int month = dt.getMonthOfYear();  // where January is 1 and December is 12
int year = dt.getYear();

设置年份,给当前时间添加两个小时

DateTime dt = new DateTime();
DateTime year2000 = dt.withYear(2000);
DateTime twoHoursLater = dt.plusHours(2);

除了基本get方法之外,每个日期时间类都为每个字段提供属性方法。这些提供的Joda Time功能完整的财富。例如,访问一个月或一年的详细信息:

  DateTime dt = new DateTime();
  String monthName = dt.monthOfYear().getAsText();
  String frenchShortName = dt.monthOfYear().getAsShortText(Locale.FRENCH);
  boolean isLeapYear = dt.year().isLeap();
  DateTime rounded = dt.dayOfMonth().roundFloorCopy();

Joda-Time提供对多个日历系统和全方位时区的支持:

//通过调用一个在年表实现工厂的方法得到了Joda Time年表
Chronology coptic = CopticChronology.getInstance();

//在东京地区获得时区
 DateTimeZone zone = DateTimeZone.forID("Asia/Tokyo");
 Chronology gregorianJuian = GJChronology.getInstance(zone);

夏令时切换到日期增加一天

  DateTime dt = new DateTime(2005, 3, 26, 12, 0, 0, 0);
  DateTime plusPeriod = dt.plus(Period.days(1));
  DateTime plusDuration = dt.plus(new Duration(24L*60L*60L*1000L));

添加一个周期(period)将增加23小时在这种情况下,而不是24,因为日光节约的变化,因此结果的时间仍然是中午。

添加一个持续时间(duration)将增加24个小时,无论什么,因此结果的时间将更改为13:00。

API路径: http://www.joda.org/joda-time/userguide.html

原文地址:https://www.cnblogs.com/xiaoQ0725/p/8079253.html