Multiplatform Date and time library for Kotlin

Overview

Klock

Klock is a Date & Time library for Multiplatform Kotlin.

It is designed to be as allocation-free as possible using Kotlin inline classes, to be consistent and portable across targets since all the code is written in Common Kotlin, and to provide an API that is powerful, fun and easy to use.

Build Status Maven Central Discord

Full Documentation: https://korlibs.soywiz.com/klock/

Some samples:

val now = DateTime.now()
val duration = 1.seconds
val later = now + 1.months + duration
val is2018Leap = Year(2018).isLeap
val daysInCurrentMonth = now.yearMonth.days
val daysInNextMonth = (now.yearMonth + 1.months).days

Usage with gradle:

def klockVersion = "..." // Find latest version in https://search.maven.org/artifact/com.soywiz.korlibs.klock/klock

repositories {
    mavenCentral()
}

// For multiplatform Kotlin
kotlin {
    sourceSets {
        commonMain {
            dependencies {
                implementation "com.soywiz.korlibs.klock:klock:$klockVersion" // Common 
            }
        }
    }
}

// For JVM
dependencies {
    implementation "com.soywiz.korlibs.klock:klock-jvm:$klockVersion"
}

Testing & Kotest

Kotest is a flexible and comprehensive testing tool for Kotlin with multiplatform support. It supports Klock adding additional matchers. For a full list of Klock Kotest matchers, check this link: https://github.com/kotest/kotest/blob/master/doc/matchers.md

And you can find a sample here: https://github.com/kotest/kotest/tree/master/kotest-assertions/kotest-assertions-klock

Comments
  • unresolved reference from gradle multiplatform build

    unresolved reference from gradle multiplatform build

    I'm not able to reference klock in a multiplatform gradle build. Not sure what I'm doing wrong. Here's a minimal example:

    build.gradle:

    buildscript {
        ext.repos = {
            jcenter()
            mavenCentral()
            maven { url "https://dl.bintray.com/soywiz/soywiz" }
        }
        repositories repos
    
        dependencies {
            classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.11'
        }
    }
    
    apply plugin: 'org.jetbrains.kotlin.multiplatform'
    
    repositories repos
    
    kotlin {
        targets {
            fromPreset(presets.jvm, 'jvm')
            fromPreset(presets.js, 'js')
        }
        sourceSets {
            commonMain {
                dependencies {
                    api "com.soywiz:klock:1.0.0"
                }
            }
            jvmMain {
                dependencies {
                   api "com.soywiz:klock-jvm:1.0.0"
                }
            }
            jsMain {
                dependencies {
                   api "com.soywiz:klock-js:1.0.0"
                }
            }
        }
    }
    
    

    src/commonMain/kotlin/main.kt

    import com.soywiz.klock.DateTime
    
    val dateTime = DateTime.now()
    
    

    Gradle error:

    :compileKotlinMetadata (Thread[Execution worker for ':',5,main]) started.
    e: /Users/asdf/klock/src/commonMain/kotlin/main.kt: (2, 8): Unresolved reference: com
    e: /Users/asdf/klock/src/commonMain/kotlin/main.kt: (5, 16): Unresolved reference: DateTime
    
    > Task :compileKotlinMetadata FAILED
    
    
    opened by martysaxton 19
  • expose PatternDateFormat regex string

    expose PatternDateFormat regex string

    This change will expose a regex string which matches the text of a correctly-formatted date, which can be composed into a larger regex.

    It achieves this by taking an already existing part of the code for the internal regex rx2, and moving it into a function which is made public.

    I need this change for a program which has to be able to match and extract timestamps in context. This will allow the regex fragment matching the timestamp to be combined with regex fragments matching the expected strings around the timestamp, for efficiently locating candidate timestamps in a single regex search.

    opened by alexbobp 12
  • JVM target error

    JVM target error

    Hi, i am facing problem after updated IntelliJ. I also have updated my kotlin version to 1.3.60

    IntelliJ IDEA 2019.2.1 (Community Edition)
    Build #IC-192.6262.58, built on August 20, 2019
    Runtime version: 11.0.3+12-b304.39 x86_64
    VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
    

    Previous version i never face any issue, but in this build, i face this error. Now I am using version 1.8.0

    Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper '-jvm-target' option
    

    FAILURE: Build failed with an exception.

    Here is the code in my commonMain folder

    var timeZone = TimeSpan((8.hours).milliseconds)
    

    I have changed my project JVM version setting to 1.6. image

    Is there anything that I have to do to solve this issue? Hopefully you can guide me on this. Thanks!

    opened by avjiang 12
  • Could not resolve com.soywiz.korlibs.klock:klock:1.4.0.

    Could not resolve com.soywiz.korlibs.klock:klock:1.4.0.

    Hello,

    I followed the instructions in the README, but I'm getting the following error :

    FAILURE: Build failed with an exception.
    
    * What went wrong:
    Could not determine the dependencies of task ':shared:compileKotlinIOS'.
    > Could not resolve all task dependencies for configuration ':shared:iOSCompileKlibraries'.
       > Could not resolve com.soywiz.korlibs.klock:klock:1.4.0.
         Required by:
             project :shared
          > Could not resolve com.soywiz.korlibs.klock:klock:1.4.0.
             > Could not parse module metadata https://dl.bintray.com/korlibs/korlibs/com/soywiz/korlibs/klock/klock/1.4.0/klock-1.4.0.module
                > Unsupported format version '1.0' specified in module metadata. This version of Gradle supports format version 0.4 only.
    
    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
    
    * Get more help at https://help.gradle.org
    
    BUILD FAILED in 5s
    

    For reference, here are the instructions that I followed.

    def klockVersion = "1.4.0"
    
    repositories {
        maven { url "https://dl.bintray.com/korlibs/korlibs" }
    }
    
    kotlin {
        sourceSets {
            commonMain {
                dependencies {
                    implementation "com.soywiz.korlibs.klock:klock:$klockVersion" // Common 
                }
            }
        }
    }
    

    settings.gradle

    enableFeaturePreview('GRADLE_METADATA')
    
    opened by Sonphil 10
  • Cannot find symbol when using library from Java

    Cannot find symbol when using library from Java

    I am on Kotlin 1.4.10 and 2.0.0-alpha.

    When I try to access properties of DateTimeTz I get an error.

    final double nowOffsetInMillis = DateTimeTz.Companion.nowLocal().getOffset();

    But then the compiler complains:

    error: cannot find symbol final double nowOffsetInMillis = DateTimeTz.Companion.nowLocal().getOffset(); ^ symbol: method getOffset() location: class DateTimeTz

    It basically happens on any property, not only 'offset'

    Any ideas?

    opened by weliem 8
  • How to deal with DateFormat if format is not always accurate

    How to deal with DateFormat if format is not always accurate

    I faced with problem of how to parse date-time with floating number of symbol positions. In other words, I am getting timestamps which were generated by java Instant and I can get either

    2020-09-30T09:20:00.993Z
    

    or

    2020-09-30T09:20:00.0Z
    

    As you can see, there is different number of positions which are used for milliseconds 993Z and 0Z hence, when I am trying to parse with following format, I am getting an error in second case

    "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"  
    

    I am asking this because there is no documentation in library code and there is no documentation of how to skip the unnecessary part of timestamp when parsing

    enhancement 
    opened by KostyaM 8
  • Use of inline classes does not play well with iOS

    Use of inline classes does not play well with iOS

    It was nice to use inline classes for some of the types, but unfortunately the Swift interoperability is greatly hampered by this. For example, a function that returns a Date or a DateTime when translated to Swift it simply becomes int32_t and the Date and DateTime classes are not accessible at all from Swift. This makes it extremely to write iOS apps dealing with dates. While it would be nice to be able to write all code in Kotlin without resorting to Swift, the fact that you can't export a UIViewController class to IOS makes that unrealistic

    question request for comments 
    opened by dalewking 8
  • Formatting with sub-second precision broken?

    Formatting with sub-second precision broken?

    Formatting with sub-second precision seems to not work:

    This:

    val badUtc = DateTime(
    date = Date(2020, 1, 4 ),
    time = Time(2, 42,55, millisecond = 500)
    val thisWorks = badUtc.format(ISO8601.DATETIME_COMPLETE)
    val thisDoesNot = badUtc.format(ISO8601.IsoDateTimeFormat("YYYYMMDDThhmmss,ss", "YYYY-MM-DDThh:mm:ss,ss"))
    println("thisWorks=$thisWorks")
    println("thisDoesNot=$thisDoesNot")
    

    Prints this:

    thisWorks=2020-01-04T02:42:55
    thisDoesNot=2020-01-04T02:42:75,50
    

    The error seems to be here:

    https://github.com/korlibs/klock/blob/f499c4a9f0590d7e23e9acdaf349d8e7deb9b162/klock/src/commonMain/kotlin/com/soywiz/klock/ISO8601.kt#L41

    opened by johanneskraem3r 8
  • Format DateTimeTz

    Format DateTimeTz

    I have DateTimeTz with correct TimeZone but when I am formatting it

    val timeFormat = DateFormat("hh:mm")
    val time = dateTimeTz.format(timeFormat)
    

    I am getting time in UTC without adjected time zone

    opened by BulatMukhutdinov 7
  • ISO8601 formats don't handle fractional seconds

    ISO8601 formats don't handle fractional seconds

    Given a timestamp as a DateTimeTz value:

    timestamp.format(ISO8601.IsoDateTimeFormat(null, "YYYY-MM-DDThh:mm:ss.sssZ"))

    does not work since it wants to try to parse the fractional part as seconds.

    bug 
    opened by j0bro 7
  • Problem with version 1.0.0 on Android Studio

    Problem with version 1.0.0 on Android Studio

    If I use version 0.2.2 I can use the library. If I upgrade to 1.0.0, gradle is doing the synchronization, but I can not compile because I don't see the DateTime class.

    Any suggestions?

    screenshot 2018-12-01 at 08 42 40
    opened by tradingstratagem 7
Releases(v2.4.13)
Owner
Kotlin cORoutine Libraries for fullstack development - https://bintray.com/korlibs/korlibs - https://github.com/korlibs
null
KotlinX multiplatform date/time library

kotlinx-datetime A multiplatform Kotlin library for working with date and time. See Using in your projects for the instructions how to setup a depende

Kotlin 1.6k Jan 5, 2023
Android NTP time library. Get the true current time impervious to device clock time changes

TrueTime for Android Make sure to check out our counterpart too: TrueTime, an NTP library for Swift. NTP client for Android. Calculate the date and ti

Instacart 1.3k Jan 4, 2023
Additions for Kotlin's date & time library kotlinx-datetime

fluid-time Additions for Kotlin's date & time library kotlinx-datetime. kotlinx-datetime is very early stage and not as actively developed as other of

Marc Knaup 39 Nov 11, 2022
A material-styled android view that provisions picking of a date, time & recurrence option, all from a single user-interface.

SublimePicker A customizable view that provisions picking of a date, time & recurrence option, all from a single user-interface. You can also view 'Su

Vikram 2.3k Jan 4, 2023
Pick a date or time on Android in style

Material DateTime Picker - Select a time/date in style Material DateTime Picker tries to offer you the date and time pickers as shown in the Material

null 4.7k Dec 29, 2022
Compose Date Picker - Select month and year

Android DatePicker with month and year build with Compose UI

Doğuş Teknoloji 47 Dec 15, 2022
A simple Cupcake Ordering App, choose flavor, pickup on a date, get order summary and send order via any other app.

Cupcake app This app contains an order flow for cupcakes with options for quantity, flavor, and pickup date. The order details get displayed on an ord

Akshat Khandelwal 0 Dec 23, 2021
MinutesAliveApp - Basic Android App that ask for your date of birth and shows your age in minutes

MinutesAliveApp Basic Android App that ask for your date of birth and shows your

JestorDev 0 Jan 30, 2022
Standalone Android widget for picking a single date from a calendar view.

TimesSquare for Android Standalone Android widget for picking a single date from a calendar view. Usage Include CalendarPickerView in your layout XML.

Square 4.4k Dec 20, 2022
java.time Kotlin extension functions library.

Java Time Kotlin extension functions. Background Java Time became integrated to the JDK as of Java 8. It was a huge improvement over its Date predeces

Sami Eljabali 31 Mar 15, 2022
A Kotlin Multiplatform library for working with dates and times

Island Time A Kotlin Multiplatform library for working with dates and times, heavily inspired by the java.time library. Features: A full set of date-t

Erik Christensen 71 Dec 28, 2022
Kmpcalendar - A calendar library and views written for kotlin multiplatform

KMPCalendarView Minimal Kotlin Multiplatform project with SwiftUI, Jetpack Compo

Anmol Verma 2 Oct 7, 2022
Joda-Time library with Android specialization

Android has built-in date and time handling - why bother with a library? If you've worked with Java's Date and Calendar classes you can probably answer this question yourself, but if not, check out Joda-Time's list of benefits.

Daniel Lew 2.6k Dec 9, 2022
Estimated Time of Arrival Bar

Estimated Time of Arrival Bar

Tek 1 Mar 12, 2022
Asimov-flagz-kt - Feature flags library based on Togglz library

Asimov Flagz Feature flags library based on Togglz library. Installation Gradle

Nicolas Bottarini 1 Jan 8, 2022
CustomizableCalendar is a library that allows you to create your calendar, customizing UI and behaviour

CustomizableCalendar This library allows you to create a completely customizable calendar. You can use CustomizableCalendar to create your calendar, c

MOLO17 216 Dec 6, 2022
A simple library which gives you custom design CalendarView with dialog functionality and event handlers.

CalendarView A simple library which gives you custom design CalendarView with dialog functionality and event handlers. 1: CalendarView Demo Screen 1.1

Shahzad Afridi (Opriday) 49 Oct 28, 2022
📅 Minimal Calendar - This calendar library is built with jetpack compose. Easy, simple, and minimal.

?? Minimal Calendar This calendar library is built with jetpack compose. Easy, simple, and minimal. Latest version The stable version of the library i

Minjae Kim 16 Sep 14, 2022
Android library for better Picker DialogFragments

DialogFragments modeled after the AOSP Clock and Calendar apps to improve UX for picking time, date, numbers, and other things.

Code-Troopers 2.7k Dec 29, 2022