Social Style Date and Time Formatting for Java

Overview

prettytime

Social Style Date and Time Formatting for Java

Learn more at https://www.ocpsoft.org/prettytime/

Java >=1.8 (Support JDK DateTime API)

PrettyTime requires Java/JDK >=1.8 as of version 5.0.0.Final or higher.

Java <=1.7

Users requiring versions of Java/JDK less than or equal to 1.7 should use PrettyTime versions in the 4.x branch: 4.0.6.Final or lower.

Android

To use prettytime in android, first add the following dependency to your app level build.gradle

implementation 'org.ocpsoft.prettytime:prettytime:4.0.4.Final'

ProGuard rules are automatically configured for you if you use the R8 shrinker (which is the default since version 3.4.0 of the Android Gradle Plugin). If you are using an older version of AGP, add the ProGuard rules from this file

Be sure to check maven central for the latest version: https://repo1.maven.org/maven2/org/ocpsoft/prettytime/prettytime/

Note: To use prettytime in projects with a minSdkVersion below 26, API desugaring is required.

DEVELOPMENT

export RELEASE_VERSION="5.x.x.Final" export SNAPSHOT_VERSION="5.x.x-SNAPSHOT"

force-release: mvn release:prepare release:perform -DskipTests=true -DdevelopmentVersion=$SNAPSHOT_VERSION -DreleaseVersion=$RELEASE_VERSION -Dtag=$RELEASE_VERSION -Darguments="-DskipTests=true -Dmaven.test.skip=true"

CODE FORMAT DEFINITIONS/CONFIG

Please use the following eclipse-style code formatter settings when submitting PRs:

https://github.com/ocpsoft/common/blob/master/ocpsoft-eclipse-code-format.xml

Comments
  • Add possibility to provide diffrent values for past and future name and pluralName

    Add possibility to provide diffrent values for past and future name and pluralName

    Hi,

    I started making Finnish translation for pretty time but realized that Finnish being awkward language needs different values for name/pluralName depending whether the duration is in the past or future. eg. 1 minute ago = 1 minuutti sitten 1 minute from now = 1 minuutin päästä 3 minutes ago = 3 minuuttia sitten 3 minutes from now = 3 minuutin päästä

    As you can (probably ;) see Finnish word minuutti (= minute) conjugation is different for past and future and it also depends if the duration is singular or not. So using just the past and future suffix leads to grammatically incorrect durations.

    I could give this a stab my self but was just wondering what would be the best way to tackle this.

    opened by ssaarinen 35
  • Android crashes

    Android crashes

    java.lang.ExceptionInInitializerError at com.sickboots.sickvideos.b.run(Unknown Source) at java.lang.Thread.run(Thread.java:856) Caused by: java.util.MissingResourceException: Can't find resource for bundle 'org.ocpsoft.prettytime.i18n.Resources_sv_SE', key '' at java.util.ResourceBundle.missingResourceException(ResourceBundle.java:237) at java.util.ResourceBundle.getBundle(ResourceBundle.java:229) at java.util.ResourceBundle.getBundle(ResourceBundle.java:160) at a.b.a.b.b.b(Unknown Source) at a.b.a.b.b.a(Unknown Source) at a.b.a.c.a(Unknown Source) at a.b.a.c.(Unknown Source) at com.sickboots.sickvideos.database.j.(Unknown Source) ... 2 more

    opened by sgehrman 24
  • ClassLoader Error

    ClassLoader Error

    I just added prettytime-integration-jstl as dependency to my pom.xml of my webproject. Running mvn tomcat7:run results in this exception:

    Aug 09, 2013 2:07:57 AM org.apache.catalina.core.ContainerBase startInternal
    SEVERE: A child container failed during start
    java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/example]]
        at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252)
        at java.util.concurrent.FutureTask.get(FutureTask.java:111)
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
        at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
        at java.util.concurrent.FutureTask.run(FutureTask.java:166)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:724)
    Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/example]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        ... 7 more
    Caused by: java.lang.LinkageError: loader constraint violation: loader (instance of org/apache/catalina/loader/WebappClassLoader) previously initiated loading for a different type with name "javax/servlet/ServletContext"
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:792)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1189)
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)
        at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:177)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5280)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 7 more
    

    I really don't know what's the problem here, but when commenting out these dependencies I can startup my webapp without any problems. My webapp is configured using JavaConfig and uses Spring. If some more information is necessary just tell me.

    opened by dtrunk90 22
  • doesn't work decorate in (t instanceof Week) in ListResourceBundle

    doesn't work decorate in (t instanceof Week) in ListResourceBundle

    week, month too and maybe other result += ">>>"+durationQuantity; // I try return anything but always return only "тиж" need "тиждень" in tests all work fine, good. in real application decorate not work.

    
                PrettyTime prettyTime = new PrettyTime(history.getDate());
                prettyTime.setLocale(new Locale("ua"));
                prettyTime.format(prettyTime.calculatePreciseDuration(new Date()))
    
    
    if (t instanceof Week) {
                return new TimeFormat() {
                    @Override
                    public String decorate(Duration duration, String time) {
                        String result = duration.isInFuture() ? "через " : "";
                        long durationQuantity = Math.abs(duration.getQuantity());
                        if (durationQuantity == 1L) {
                            result += time + "день";
                        } else {
                            result += time + "ні";
                        }
                        result += ">>>"+durationQuantity;
                        if (duration.isInPast()) {
                            result += " тому";
                        }
                        return result;
                    }
    
                    @Override
                    public String decorateUnrounded(Duration duration, String time) {
                        String result = duration.isInFuture() ? "через " : "";
                        long durationQuantity = Math.abs(duration.getQuantity());
                        if (durationQuantity == 1L) {
                            result += time + "день";
                        } else {
                            result += time + "ні";
                        }
                        if (duration.isInPast()) {
                            result += " тому";
                        }
                        result += ">>>"+durationQuantity;
                        return result;
                    }
    
                    @Override
                    public String format(Duration duration) {
                        return Math.abs(duration.getQuantity()) + " тиж";
                    }
    
                    @Override
                    public String formatUnrounded(Duration duration) {
                        return Math.abs(duration.getQuantity()) + " тиж";
                    }
                };
            }
    
    opened by 452 20
  • Support for displaying precise duration, i.e. <3 days 4 hours ago>

    Support for displaying precise duration, i.e. <3 days 4 hours ago>

    Please consider applying this upgrade. Currently rounding is forced, so in fact there is no way to display precise time. One can calculate list of Durations, but then if we have for example (3 hours, 45 minutes, 55 seconds) to display, after formatting each Duration separately we end up with: (4 hours, 46 minutes, 55 seconds). This patch introduces optional rounding and optional decorating (but old interface remains intact with previous defaults) and handy interface to do so. Calling PrettyTime.format(List) can give results like: ''3 days 22 hours 34 minutes from now".

    opened by nessumo 15
  • No grammatical cases in translations

    No grammatical cases in translations

    When using the formatDuration(Date) method in Locale.GERMAN the translations are not accurate.

    Problem

    • Days: 5 Tagen should be 5 Tage
    • Months: 5 Monaten should be 5 Monate
    • Years: 5 Jahren should be 5 Jahre
    • Decade: 5 Jahrzenten should be 5 Jahrzente
    • Century: 5 Jahrhunderten should be 5 Jahrhunderte
    • Millenium: 5 Jahrtausenden should be 5 Jahrtausende

    However These words are correct for the format(Date) method. Example:

    • vor 5 Tagen
    • vor 5 Monaten
    • etc.

    Explanation

    Nouns do have a case (Kasus) when used in a sentence in german (and some other languages?). (see https://en.wikipedia.org/wiki/Grammatical_case)

    This means that words would need to be translated for the different grammatical cases.

    Instead of just this translation:

    { "SecondPluralName", "Sekunden" }
    

    You'd need to have these:

    { "SecondPluralNameNominative", "Tage" }
    { "SecondPluralNameDative", "Tagen" }
    

    Which would be very annoying.

    Possible Solution

    You should translate whole sentences and parameterize them instead of trying to translate single words and then later sticking them together, because that will result in errors like these in the long term.

    Highly relevant video: https://www.youtube.com/watch?v=GAgp7nXdkLU

    opened by hertg 13
  •  5 minutes is default minimum duration?

    5 minutes is default minimum duration?

    It looks like by default, all durations below 5 minutes are labelled "moments ago".

    Is there a simple way to control this tolerance? Is it rounding?

    I would like to show:

    • minutes ago
    • seconds ago

    Milliseconds ago are fine to show as "moments ago".

    On the website, it even says: Convert elapsed timestamps, like, "in 3 minutes!"

    Repost from forums: http://ocpsoft.org/support/topic/5-minutes-is-default-minimum-duration

    opened by alexanderhawley 13
  • Use Java 8 APIs.

    Use Java 8 APIs.

    Make use of features added in Java 8, and add methods that accept the java.time date/time types.

    This fixes https://github.com/ocpsoft/prettytime/issues/109.

    opened by Isira-Seneviratne 7
  • Added russian language support

    Added russian language support

    Also, i suggest incorporating well-tested gettext I10n expressions for determining plural form of specific language word:

    http://translate.sourceforge.net/wiki/l10n/pluralforms

    opened by iamtakingiteasy 6
  • Fixing DecadeName and DecadePluralName (typo)

    Fixing DecadeName and DecadePluralName (typo)

    I used PrettyTime in a personal project and @fbiville realized there was a typo in French... So I quickly went to GitHub to make a pull request before he could do so :) .

    In French, DecadeName is written décennie, not décénie.

    Very nice project by the way!

    opened by pyricau 6
  • Couldn't find the nlp package in Android Studio

    Couldn't find the nlp package in Android Studio

    I added the dependency to my app build gradle. I see org.ocpsoft.prettytime imported in my external library, and packages such as Duration, LocaleAware, but not the nlp package. I'm using Android Studio 3.5.0. Did I miss anything?

    opened by Yuhanlolo 5
  • Can not download from pretty-time dependency,

    Can not download from pretty-time dependency, "could not find artifact" in IntelliJ Idea

    Hello. I'm doing a tutorial of Java Brains and he use your team dependency at 30:38 , here is the link: https://youtu.be/tfmFRrPz52s

    but things is going wrong when I import your dependency and get some error, I think that it is from your side. Here is the log and I'm using IntelliJ idea, maven project. "Could not find artifact org.ocpsoft.prettytime:prettytime-integration-jsf:pom:unknown in central (https://repo.maven.apache.org/maven2) " 8 5 This is when I add version to the dependency, seems nothing downloaded 8 6 Because then I can not use PrettyTime object in my code 8 7

    opened by ThanhTC266 2
  • Make use of java.time's ChronoUnit, Duration and Period.

    Make use of java.time's ChronoUnit, Duration and Period.

    The PrettyTime codebase could be refactored to make use of the ChronoUnit enum and Duration and Period classes, instead of defining the current implementations manually.

    opened by Isira-Seneviratne 1
  • Enforce code formatting of changed files

    Enforce code formatting of changed files

    This commit introduces the maven spotless plugin to the project that can format the source code using "mvn spotless:apply" based on the configuration in the parent pom.xml. Also it will perform a spotless:check during the verify phase to ensure that all files are properly formatted.

    opened by obecker 2
  • Stabilize unit tests

    Stabilize unit tests

    When trying to contribute to this project, I was very surprised to see that a lot of unit tests are failing.

    After digging into the code I realized that this results most probably from using current dates in the tests. However, this is a problem because a year in reality has a different amount of millis depending on the current date, but a year in prettytime has always 31556925960 millis (about 365,242 days). So current date minus 1 year will format as "one year ago" in a leap year (i.e. the duration contains the leap day), but as "12 months ago" in all other years.

    To fix this all tests should be based on defined dates, so they will produces the same results no matter when the tests are executed.

    See the adjusted test in https://github.com/ocpsoft/prettytime/pull/229 as an example

    opened by obecker 2
  • Duration of 60 seconds or less formats as empty string

    Duration of 60 seconds or less formats as empty string

    When I try to format duration of 60 seconds or less it gives me empty string regardless of locale.

            val seconds = 30L
            val locale = Locale("en", "US")
            val t = PrettyTime(Date(1000 * seconds), locale)
                .calculatePreciseDuration(Date(0))
            val result = PrettyTime(locale).formatDurationUnrounded(t)
    
            assertThat(result).isEqualTo("30 seconds")
    
    opened by andrzejpolis 0
A Social Media Application with a Chatbot.

Acro Chat A Social Media Android app build in using Features- Posts, Chat with Users, Profile Page, Chat bot Preview Home Page Messages Chat Bot Licen

Sachin Lohar 14 Aug 3, 2022
Library for easy work with Facebook, Twitter, LinkedIn and Google on Android

THIS PROJECT IS NO LONGER MAINTAINED, FEEL FREE TO FORK AND FIX IT FOR YOUR NEEDS There is also an Android Library that is being maintained, CloudRail

Anton Krasov 1k Dec 18, 2022
📲 Android Application to track any user activity on Github built using the Github Developers API. Used Retrofit to fetch data and MVVM Architecture.

Github Visualizer ?? Android Application to track any user activity on Github built using the Github Developers Api. A sample application to demonstra

Dheeraj Kotwani 104 Dec 28, 2022
Material Design ready and feature rich Twitter/Mastodon/Fanfou app for Android 4.1+.

Twidere for Android Material Design ready and feature rich Twitter/Mastodon/Fanfou app for Android 4.1+. Enjoy Fediverse now! Twidere-Android is maint

Twidere Project 2.7k Jan 1, 2023
Share twitter url to this app, and you will be redirected.

twitter2nitter - redirect twitter to nitter Share twitter url to this app, and you will be redirected. Redirect works for: Open twitter url with twitt

null 14 Dec 20, 2022
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 Jan 4, 2023
Android library contain custom realisation of EditText component for masking and formatting input text

Masked-Edittext Masked-Edittext android library EditText widget wrapper add masking and formatting input text functionality. Install Maven <dependency

Evgeny Safronov 600 Nov 29, 2022
Asimov-time-kt - Useful time and date related functions and extensions

asimov/time Useful time and date related functions and extensions. Installation

Nicolas Bottarini 1 Jan 7, 2022
Social share - Social Sharing Plugin For Private Use only (Code without error checking)

Flutter Social Share plugin for sharing file to media with multiple (More option

MP IT SPACE 0 Mar 19, 2022
Time-DatePicker - A Simple Time Date Picker With Kotlin

Time-DatePicker Time.DatePicker.mp4

Faysal Hossain 0 Jan 19, 2022
Nepali Date Picker library in Jetpack compose for android with Date conversion from BS to AD and vice-versa

Nepali Date picker Converter - Re in Compose This is a re-work of Nepali Date Picker Converter in jetpack compose and kotlin. English Locale Nepali Lo

Kiran Gyawali 4 Dec 23, 2022
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
Java/Kotlin lightweight implementation of RFC-6238 and RFC-4226 to generate and validate time-based one-time passwords (TOTP).

1time Java/Kotlin lightweight implementation of RFC-6238 and RFC-4226 to generate and validate time-based one-time passwords (TOTP). Maven / gradle de

Atlassian Labs 31 Dec 21, 2022
iOS style scroll wheel (style similar to UIPickerView)

WheelPicker iOS-style scroll wheel picker Read this in other languages: Feature Day / Night Mode Support Customizable style Support circular scro

Tian Yiyan 21 Dec 30, 2022
Multiplatform Date and time library for Kotlin

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 consis

null 681 Dec 19, 2022
MaterialPickers-in-android - A simple android project that shows how to create material pickers for date and time

MaterialPickers-in-android A simple android project that shows how to create mat

Segun Francis 2 Apr 28, 2022
Material (Gregorian - Hijri) Date & Time Picker

Hijri Date Picker (UmAlQuraCalendar) This library offers a hijri (Islamic Calendar) Date Picker designed on Google's Material Design Principals For Pi

Abdullah Alhazmy 130 Dec 27, 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
Material (Gregorian - Hijri) Date & Time Picker

Hijri Date Picker (UmAlQuraCalendar) This library offers a hijri (Islamic Calendar) Date Picker designed on Google's Material Design Principals For Pi

Abdullah Alhazmy 130 Dec 27, 2022