Android date-time manipulation library

bav*_*aza 4 java android calendar date

Coming from C#, I got used to the slick interface DateTime and TimeSpan offer. With these, I can access date-time parts (Year, Month, Seconds, etc.), the underlying Ticks, subtract dates, add time deltas and so on.

As a Java/Android newbie, I understand that the equivalent Java Date class used to have these accessors, but they were removed for back-compatibility reasons. The suggested alternative is to use a Calendar object, but I find its interface cumbersome compared with .Net's.

Is there an equivalent Java library to ease the manipulation of Date objects in Android?

Jig*_*shi 7

Update:

As @basil pointed out in the comment below

The Joda-Time project is now in maintenance mode. Its creator, Stephen Colebourne, went on to lead JSR 310 defining the java.time classes built into Java 8+. See Tutorial by Oracle. – Basil Bourque 1 min ago

you can use joda-time it is an external library, Date & Calendar are basic API provided, with java 8 it has added much better api for date time but for android for now you can use joda tiem


Bas*_*que 5

java.time

其他答案已经过时。

乔达时间框架是一个非常成功和精彩的作品。但是,由Stephen Colbourne领导的其创建者进行了完全的重写和重新设计,以生成内置于Java 8及更高版本中的java.time框架。

ThreeTen-Backport项目中,许多java.time功能都已反向移植到Java 6和7 。这项工作在ThreeTenABP项目中进一步适用于Android 。

Joda-Time继续保持下去。但是团队建议我们在方便时尽快迁移到java.time。未来的创新工作将在Three.Ten-Extra项目中纳入java.time及其扩展。

我建议您在新代码中使用java.time。无需删除Joda-Time。这两个框架可以共存于您的项目中。请注意一下您的import声明,因为其中有一些类在两个框架之间共享一个名称。以后,一旦您对java.time感到满意,就可以考虑重新使用旧代码以逐步淘汰Joda-Time。

ZonedDateTime

ZonedDateTime上课。它有你问的方法getYeargetHour以及这样的。

所述Instant类表示UTC片刻解析为纳秒(比其他库/系统中使用的毫秒,微秒更细)。这是java.time的基本构建类。

我可以访问日期时间部分(年,月,秒等),基础的刻度,减去日期,添加时间增量等。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
int year = zdt.getYear() ;
int hour = zdt.getHour() ;
int second = zdt.getSecond() ;
long millisecondsSinceEpochOfFirstMomentOf1970InUtc = zdt.toInstant().toEpochMilli() ;
ZonedDateTime earlier = zdt.minusDays( 3 ) ;  // Three days prior.
Duration duration = Duration.of( earlier , zdt ) ;  // Scale of 24-hour days (not attached to the calendar), hours, minutes, seconds, and fraction of second.
Period period = Period.of( earlier.toLocalDate() , zdt.toLocalDate() ) ;  // Scale of year-months-days. 
Run Code Online (Sandbox Code Playgroud)

时间跨度

有关时间轴未附带的时间跨度,请参见PeriodDuration类。各种日期时间类都有用于添加或减去此类对象的数学方法。


关于java.time

java.time框架是建立在Java 8和更高版本。这些类取代麻烦的老传统日期时间类,如java.util.DateCalendar,和SimpleDateFormat

要了解更多信息,请参见Oracle教程。并在Stack Overflow中搜索许多示例和说明。规格为JSR 310

现在处于维护模式Joda-Time项目建议迁移到java.time类。

您可以直接与数据库交换java.time对象。使用与JDBC 4.2兼容的JDBC驱动程序或更高版本。不需要字符串,不需要java.sql.*类。

在哪里获取java.time类?

与哪个版本的Java或Android一起使用的哪个java.time库的表