Kotlin Android – Easier Date and Time Options

0
User Management System
Learn Kotlin, Retrofit, MVVM and MySQL using this all-in-one app. It is designed to be beginner friendly.

In most apps we build, date and time is a feature we tend to use. The standard options availed by java.util do work well but they are not quite effective and for something so basic, they tend to need alot of custom solutions. This introduces possibilities of errors as we add lots of boilerplate code in our project. But there are solutions that have already been implemented, and that we can easily incorporate into our applications. These tend to do the job for us mostly using a single line of code.

Daily Chores App
Download Daily Chores App for FREE and see how we've used the horizontal datepicker to filter daily chores.
5

 

For example with these libraries you will be able to easily perform the following:

  • Get date today, yesterday etc.
  • Get date 2 years from now or from the past.
  • Add a certain number to a given date etc.

You do these with a single line of code. Let's look at the libraries:

 

(a). Tempo

  • First Solution

tempo

Kotlin intuitive java.util.Date extensions.

Build Status

Download License

Usage

val now: Date = Tempo.now               //=> now
now + 1.week                            //=> next week 
now - 2.days                            //=> day before yesterday
now + (3.weeks - 4.days + 5.hours)      //=> somewhere in 2 and a half weeks

Tempo.tomorrow                          //=> tomorrow
Tempo.yesterday                         //=> yesterday
1.day.ago                               //=> yesterday
3.weeks.ago                             //=> 3 weeks ago
5.years.forward                         //=> five years in the future 

Initialize by specifying date components

Tempo.with(year = 1990, month = 1, day = 21)    //=> 1990/01/21
Tempo.with(year = 2019, month = 6, day = 26, hour = 18, minute = 58, second = 31, millisecond = 777)

Initialize by changing date components

Tempo.now.with(month = 12, day = 25)    //=> this year's christmas
Date().with(month = 12, day = 25)       //=> this year's christmas

// shortcuts
Tempo.now.beginningOfYear     //=> new year's day
Tempo.now.endOfYear           //=> new year's eve

Check day of the week / properties

Tempo.now.isMonday
Tempo.now.isTuesday
Tempo.now.isWednesday
Tempo.now.isThursday
Tempo.now.isFriday
Tempo.now.isSaturday
Tempo.now.isSunday
Tempo.now.isWeekend
Tempo.now.isWeekday

Tempo.now.isToday                       // true
Tempo.tomorrow.isToday                  // false
Tempo.tomorrow.isTomorrow               // true
Tempo.yesterday.isYesterday             // true

Format and parse

5.minutes.forward.toString("yyyy-MM-dd HH:mm:ss")
//=> "2019-06-11 12:05:00"

"1988-03-02".toDate("yyyy-MM-dd")
//=> Tempo.with(year = 1988, month = 3, day = 2)

Compare dates

1.day.ago > 2.days.ago                  // true
1.day.ago in 2.days.ago..Tempo.now      // true

Install

Latest version =

Download

dependencies {
  implementation 'com.github.cesarferreira:tempo:+'
}

Notice

Licence

Copyright 2019 Cesar Ferreira

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 

(b). Karamba

Karamba is not only a datetime library, it's actually a utilities library but has some easy to use datetime functions alongside some commonlyused functionalities in android development.

  • Second Solution

karamba

A collection of useful Kotlin extension for Android

karamba

Install

Add to gradle in allprojects

maven { url 'https://jitpack.io' }

then add this

compile 'com.github.matteocrippa:karamba:1.2.0'

Usage

Karamba provides you a list of different and useful extensions for your project, here the list organized by the type extended.

General

  • support(apiVersion), lambda that allow you to run code only if current SDK is up to specified one
  • supportKitkat(), lambda that checks if kitkat is supported and run the code
  • supportLollipop(), lambda that checks if lollipop is supported and run the code

Bitmap

  • base64(), produces a base64 representation of the current bitmap
  • resize(height, width), resize the current bitmap to new format

Boolean

  • toggle(), handle the bool as a toogle changing the value to opposite one, then the new value is returned (not yet possible to change this)
  • random(), returns a random boolean value, then the new value is returned (not yet possible to change this)

Date

  • convertTo(format), converts current date to a custom format provided as argument (eg. dd-MM-yy HH:mm)
  • toCalendar(), converts current date to Calendar
  • isFuture(), returns true if date is in the future
  • isPast(), returns true if date is in the past
  • isToday(), returns if current date is today
  • isTomorrow(), returns if current date is tomorrow
  • isYesterday(), returns if current date is yesterday
  • today(), returns today's date
  • tomorrow(), returns tomorrow's date
  • yesterday(), returns yesterday's date
  • hour(), returns current date hour as number
  • minute(), returns current date minutes as number
  • second(), returns current date seconds as number
  • month(), returns current date month as number
  • monthName(), returns current date month as long name
  • year(), returns current date year as number
  • day(), returns current date day as number
  • dayOfWeek(), returns current date day of the week as number
  • dayOfWeekName(), returns current date weekday as string
  • dayOfYear(), returns current date day of year as number

Double

  • localCurrency(currency), converts current double to the currency format passed as argument (eg. EUR)
  • celsiusToFahrenheit(), converts current double to fahrenheit
  • fahrenheitToCelsius(), converts current double to celsius

Drawable

  • toBitmap(), converts the current drawable in Bitmap

Int

  • readableDistanceFromMeters(), converts an int amount of meters in a readable meter, kilometers distance
  • commaSeparatedId(), converts an array of int, in a string of comma separated items
  • random(), provides a random number in the range provided (eg. (0..10).random())

String

  • isValidEmail(), returns if current string is a valid email
  • isUrl(), returns if current string is a valid url
  • isNumeric(), returns if current string contains a number
  • isPhoneNumber(), returns if current string contains a phone number
  • random(lenght), returns a random string of provided length
  • toBitmap(), convert current base64 string into Bitmap
  • ellipsize(chars), ellipsizes the current string, truncating at defined amount of characters
  • toDate(format), converts current string in a Date object using the provided format
  • plainText(), removes all html formatting from current string
  • toCamelCase(), camel case the current string current string

View

  • toBitmap(), converts current view into Bitmap

Credits

Icon is taken by free emojii set by Vincent Le Moign

Full Applications

We have some of our apps which have extensively used datetime libraries. Use them to learn by doing:

Added to wishlistRemoved from wishlist 0
Add to compare
Lana : A Daily Lessons App – RxJava2+Room+Clean Architecture+MVVM
Sale
I have created this project to help you learn the following core concepts that we will be using in alot of our projects henceforth:
  1. RxJava2
  2. Room Full CRUD
  3. Proper Clean Architecture (Dividing our app into domain and infrastructure layers)
  4. Single Page Design
  5. Full offline app creation
Read the features and documentation here.
Added to wishlistRemoved from wishlist 0
Add to compare
Daily Chores App
Sale
1 year ago

Daily Chores Productivity App

$5.00 $0.00
Daily Chores App is a full android application ready for Play Store. All you need to do is change name, colors, logos etc and make it your own. Of course as a programmer you can extend it with more features. The source code is high quality and given that we've utilized Clean Architecture as a design pattern, you can easily understand and follow the code.  
Added to wishlistRemoved from wishlist 0
Add to compare
kotlin android task planner splash page
Sale
This is a full offline task planner app created exclusively in Kotlin. It is extremely beautiful and simple to use. The app allows users to create tasks and save them in database. We use MVVM design pattern. Read Full Features and Documentation here.

 

Android MySQL Retrofit2 Multipart CRUD,Search,Pagination rating

When I was a 2nd year Software Engineering student, I buillt a now defunct online tool called Camposha(from Campus Share) using my then favorite language C#(ASP.NET) to compete OLX in my country(Kenya). The idea was to target campus students in Kenya. I got a few hundred signups but competing OLX proved too daunting. I decided to focus on my studies, learning other languages like Java,Python,Kotlin etc while meanwhile publishing tutorials at my YouTube Channel ProgrammingWizards TV which led to this site(camposha.info). Say hello or post me a suggestion: oclemmi@gmail.com . Follow me below; Github , and on my channel: ProgrammingWizards TV

We will be happy to hear your thoughts

Leave a reply

fifty eight − fifty four =

Reset Password
Compare items
  • Total (0)
Compare
0
Shopping cart