Time


Source link: https://github.com/kizitonwose/Time

Time

This library is made for you if you have ever written something like this:

val duration = 10 * 1000

to represent a duration of 10 seconds(in milliseconds) because most methods in Kotlin/Java take duration parameters in milliseconds.

Usage

Showcase

val tenSeconds = 10.seconds val fiveMinutes = 5.minutes val twoHours = 2.hours val threeDays = 3.days val tenMinutesFromNow = Calendar.getInstance() + 10.minutes val tenSecondsInMilliseconds = 10.seconds.inMilliseconds

Basics

The main advantage of the library is that all time units are strongly-typed. So, for example:

val tenMinutes = 10.minutes

In the example above, tenMinutes will be of type Interval<Minute>. There are seven time units available, from nanoseconds to days:

val tenNanoseconds = 10.nanoseconds  // type is Interval<Nanosecond>
val tenMicroseconds = 10.microseconds  // type is Interval<Microsecond>
val tenMilliseconds = 10.milliseconds  // type is Interval<Millisecond>
val tenSeconds = 10.seconds  // type is Interval<Second>
val tenMinutes = 10.minutes  // type is Interval<Minute>
val tenHours = 10.hours  // type is Interval<Hour>
val tenDays = 10.days  // type is Interval<Day>

Operations

You can perform all basic arithmetic operations on time intervals, even of different units:

val duration = 10.minutes + 15.seconds - 3.minutes + 2.hours // Interval<Minute> val doubled = duration * 2  val seconds = 10.seconds + 3.minutes // Interval<Second>

You can also use these operations on Calendar:

val twoHoursLater = Calendar.getInstance() + 2.hours

Conversions

Time intervals are easily convertible:

val twoMinutesInSeconds = 2.minutes.inSeconds // Interval<Second> val fourDaysInHours = 4.days.inHours // Interval<Hour>

You can also use the converted() method, although you would rarely need to:

val tenMinutesInSeconds: Interval<Second> = 10.minutes.converted()

Comparison

You can compare different time units as well:

50.seconds < 2.hours // true 120.minutes == 2.hours // true 100.milliseconds > 2.seconds // false 48.hours in 2.days // true

Creating your own time units

If, for some reason, you need to create your own time unit, that's super easy to do:

class Week : TimeUnit {

  // number of seconds in one week
  override val timeIntervalRatio = 604800.0 
}

Now you can use it like any other time unit:

val fiveWeeks = Interval<Week>(5)

For the sake of convenience, don't forget to write those handy extensions:

class Week : TimeUnit {

  override val timeIntervalRatio = 604800.0 
}
  val Number.weeks: Interval<Week>
  get() = Interval(this)  val Interval<TimeUnit>.inWeeks: Interval<Week>
  get() = converted()

Now you can write:

val fiveWeeks = 5.weeks // Interval<Week>

You can also easily convert to weeks:

val valueInWeeks = 14.days.inWeeks // Interval<Week>

Extras

The library includes some handy extensions for some classes:

val now = Calendar.getInstance()  val sixHoursLater = now + 6.hours val fourDaysAgo = now - 4.days
val timer = Timer() timer.schedule(10.seconds) {

  println("This block will be called in 10 seconds") 
}

The library also includes extensions for Android's Handler class, this is only available if you compile the "time-android" module.

val handler = Handler() handler.postDelayed({

  Log.i("TAG", "This will be printed to the Logcat in 2 minutes") 
}
, 2.minutes)

More extensions will be added to the library in the future.

Conversion safety everywhere

For time-related methods in other third-party libraries in your project, if such methods are frequently used, it's best to write extention functions that let you use the time units in this libary in those methods. This is mostly just one line of code.

If such methods aren't frequently used, you can still benefit from the conversion safety that comes with this library.

An example method in a third-party library that does something after a delay period in milliseconds:

class Person {

  fun doSomething(delayMillis: Long) {

// method body
  
}
 
}

To call the method above with a value of 5 minutes, one would usually write:

val person = Person() person.doSomething(5 * 60 * 1000)

The above line can be written in a safer and clearer way using this library:

val person = Person() person.doSomething(5.minutes.inMilliseconds.longValue)

If the method is frequently used, you can write an extension function:

fun Person.doSomething(delay: Interval<TimeUnit>) {

  doSomething(delay.inMilliseconds.longValue) 
}

Now you can write:

val person = Person() person.doSomething(5.minutes)

Installation

Add the JitPack repository to your build.gradle:

allprojects {
  repositories {

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

  
}
 
}

Add the dependency to your build.gradle:

  • For non-Android projects:
dependencies {

  compile 'com.github.kizitonwose.time:time:1.0.1' 
}
  • For Android projects:
dependencies {

  compile 'com.github.kizitonwose.time:time-android:1.0.1' 
}

Contributing

The goal is for the library to be used wherever possible. If there are extension functions or features you think the library should have, feel free to add them and send a pull request or open an issue. Core Kotlin extensions belong in the " time" module while Android extensions belong in " time-android" module.

Inspiration

Time was inspired by a Swift library of the same name - Time.

The API of Time(Kotlin) has been designed to be as close as possible to Time(Swift) for consistency and because the two languages have many similarities. Check out Time(Swift) if you want a library with the same functionality in Swift.

License

Time is distributed under the MIT license. See LICENSE for details.

Resources

A custom EditText for Android that shows its text according to a pre-defined pattern.

Plugin which shows you the bugs from your Bugsnag projects + few useful features.

Options:

  • Add, edit bugsnag accounts
  • Show all projects from all accounts
  • Fetch errors of selected project
  • See full stacktrace of the error
  • Double click on the error and go the java class to the right line in the editor
  • Customize view columns

SQLite Model Generator Eclipse plugin allows to generate SQLite models for Android projects using JSON schema file.

android-localization-helper helps to find missing or obsolete translations for android resources.

Usage:

alh.sh /path/to/android/project [arrays.xml]

You must specify android project folder. Second parameter is optional, it specifies resources filename (strings.xml by default).

This plugin generates Android string resource XML files from CSV file. Generation has to be invoked as additional gradle task.

Supported features:

  • non-translatable resources - translatable="false" XML attribute
  • auto-escaping double quotes, apostrophes and newlines
  • auto-quoting leading and trailing spaces
  • syntax validation - duplicated, empty, invalid names detection
  • comments

TokenAutoComplete is a Android Gmail style token auto-complete text field and filter. It's designed to have an extremely simple API to make it easy for anyone to implement this functionality while still exposing enough customization to let you make it awesome.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes