Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What class should I use for Date's in Android?

Tags:

java

date

android

I'm currently making an app for android, but I'm unsure which class is actually best to use.

What I need to do with the dates that I'm working with is things such as comparing the dates, getting the difference between them, and date calculations (such as adding/subtracting a small period of time such as two weeks or a month to any given date).

I know that the standard Date class in the Java API is horrible, so I'm just wondering which classes are recommended?

I've seen the GregorianCalendar class, and the Joda Time library. However, I read on a post that due to the size of the Joda Time library, it wasn't recommended for apps.

Any help would be much appreciated. ^^

Edit: Upon a comment from 404notfound, I decided to go with the Calendar interface. This is due to the Calendar interface automatically using the best implementation of it based on the locale and time zone of the user's device. This would make it more flexible over its implementation of the GregorianCalendar (or other specific implementations) in terms of places you can roll it out to.

Hope this is helpful to anyone else with the same conundrum!

Edit #2: After further look into the link provided by Nguyễn Hoài Nam, I've went with the ThreeTenABP library, as it's a wrapper for the new Time class featured in Java 8, and will prove to be more fluent in use than a Calendar approach.

like image 204
Liam Kelly Avatar asked Jul 24 '15 01:07

Liam Kelly


1 Answers

I would recommend looking at the ThreeTenABP library as a better alternative (as that's what I've migrated a similar application to use). This library is a backport for Android of ThreeTenBP, which in turn is a backport for Java 6 of the latest Java 8's Date Time API (same creator). (I would encourage you to review the Java 8 Date Time API pros/cons out there first.) Note that ThreeTenBP provides some similar verbs with Joda Time so you won't have hard time migrating them. Last, as noticed in this lib, method count, lib size etc is always a problem in Android. This lib solve that.

Edited to add a usage guide.

  • Add this lib to your build.gradle

    compile 'com.jakewharton.threetenabp:threetenabp:1.0.1'

  • Create your Application class if you didn't. For example, your package is: com.example.app, place a new file named MyApplication.java under that package. Snippet here MyApplication.

  • Update your AndroidManifest.xml <application> tag: add this line right under <application : android:name=".MyApplication"

  • Run your app.

like image 62
Nguyễn Hoài Nam Avatar answered Oct 06 '22 16:10

Nguyễn Hoài Nam