ocpsoft / prettytime Goto Github PK
View Code? Open in Web Editor NEWSocial Style Date and Time Formatting for Java
Home Page: http://ocpsoft.org/prettytime/
License: Apache License 2.0
Social Style Date and Time Formatting for Java
Home Page: http://ocpsoft.org/prettytime/
License: Apache License 2.0
http://en.wikipedia.org/wiki/Dual_grammatical_number
First of all thanks for this cool library! I was surprised that Locale for my language (Slovenian) exists but I've noticed that it is using plural for dual grammatical number phrases. An interesting fact is that Slovenian is now the only nationaly accepted language with dual, even in standard Lithuanian the dual is now nearly obsolete. So we are in company with exinct languages like: Sanskrit, Ancient Greek, Gothic, Scottish Gaelic and Semitic languages. Haha how cool is that :)
Example:
SINGULAR DUAL PLURAL
1 week ago 2 weeks ago 3 weeks ago
1 teden nazaj 2 tedna nazaj 3 tedne nazaj
I need suggestions for implementation!
PrettyTime.calculatePreciseDuration() returns only the most significant Duration for the Dates in the past.
How can I translate prettytime-nlp recognition in other languages?
Ex. if I put ("Ci vediamo domani") it will return tomorrow's date
When running on my laptop with a French Locale :
Failed tests: testParsePrettyTimeTime(org.ocpsoft.prettytime.nlp.PrettyTimeParserTest): null expected:<[3 days ago]> but was:<[il y a 3 jours]>
testParseSyntax(org.ocpsoft.prettytime.nlp.PrettyTimeParserTest): null expected:<[3 days ago]> but was:<[il y a 3 jours]>
testParseSyntaxRecurring(org.ocpsoft.prettytime.nlp.PrettyTimeParserTest): null expected:<[3 days from now]> but was:<[dans 3 jours]>
Tests should force the English Locale
Hi there and thanks for the great work. The following returns "moments ago 2 hours" when it should be "2 hours ago" or "2 hours 2 minutes ago":
new PrettyTime().calculatePreciseDuration(
new Date(System.currentTimeMillis() - 2*60*60*1000 - 2*60*1000))
Hi all, I just noticed that the PrettyTimeParser() is not able to parse a simple year input, for example: parse("2014"). It seems that the parser treats this input as a time instant "20:14". So I just point out this issue for your consideration.
Hi.
I tried you jar library from your site and it has broken set Locale. It always show String from Locale.getDefault(); I tested it on source files and it works. Please update jar file on web.
The reference timestamp of a cached PrettyTime instance is not up-to-date during invocation of getAsString() - it's only set once, during instantiation. So that PrettyTimeConverter will always return formatted string referenced to the time the instance was created and not "now". Actually I haven't tested this but I ran into the same issue with a similar PrettyTime integration component.
PrettyTime.format(Duration) could work in this use case, however the API does not provide a method to construct Duration instances. A simple Durations util class with static method createDuration(Date reference, Date then) might be useful.
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.
I have encountered a situation where PrettyTime appears to get stuck in an infinite loop. The following code reproduces it every time.
public class PreciseDurationTimeFormatter {
private PrettyTime formatter;
public PreciseDurationTimeFormatter() {
formatter = new PrettyTime();
formatter.removeUnit(JustNow.class);
formatter.removeUnit(Millisecond.class);
}
/**
* Return the human readable duration for a given number of milliseconds.
*
* @param time the number of milliseconds
* @return the string representing the number of milliseconds in a human readable format.
*/
@Override
public String getHumanReadableDuration(long time) {
// This is a bit of a hack so it only works with the english langauge
Date date = new Date(System.currentTimeMillis() + time);
List<Duration> durationList = formatter.calculatePreciseDuration(date);
String duration = formatter.format(durationList);
duration = duration.replaceAll("from now", "");
duration = duration.replaceAll("ago", "");
return duration.trim();
}
}
Then to create the loop simply call getHumanReadableDuration
twice with any argument you like. It is worth noting if you initialize a new instance of PrettyTime in getHumanReadableDuration
for each request this doesn't happen, so I am assuming that is what is recommended. Regardless I do not think you would intend this behaviour to happen.
This is occurring on version 3.0.2-Final
.
Hi,
one 'o' too much in afternoon...
Just found it while trying to find out how to make this more i18n... any tips on that? Guess it makes more sense to look at opennlp/uima in that case?
--Alex
jsf/src/main/resources/META-INF/faces-config.xml
has the wrong class listed:
<converter>
<converter-id>org.ocpsoft.PrettyTimeConverter</converter-id>
<converter-class>org.ocpsoft.pretty.time.web.jsf.PrettyTimeConverter</converter-class>
</converter>
should be:
<converter>
<converter-id>org.ocpsoft.PrettyTimeConverter</converter-id>
<converter-class>org.ocpsoft.prettytime.jsf.PrettyTimeConverter</converter-class>
</converter>
"Fork us on GitHub" leads to the rewrite project
Hello, thanks for this great library.
On Android Studio 0.5.8, with dependency:
compile 'org.ocpsoft.prettytime:prettytime:2.1.1.Final@jar'
the library works great for all the languages I need (English, French, Japanese, etc) except for Indonesian (defaults to english).
I've tried:
PrettyTime prettyTime = new PrettyTime(new Locale(myLocale));
with myLocale = "in_ID" => English
with myLocale = "id" => English
I know that maybe this is out of scope of this library but I think it would be so useful having in same library the inverse path, so instead of transforming a Date to String something like 10 minutes from now we could do String to Date, so when you pass an String like 10 minutes from now the library creates a new Date and adds 10 minutes.
What do you think?
I'm dealing with dates like this one: 06/23/2015 00:00:00 (time always at midnight).
So it made sense to comment out some units:
private void initTimeUnits()
{
addUnit(new JustNow());
//addUnit(new Millisecond());
//addUnit(new Second());
//addUnit(new Minute());
//addUnit(new Hour());
addUnit(new Day());
addUnit(new Week());
addUnit(new Month());
addUnit(new Year());
addUnit(new Decade());
addUnit(new Century());
addUnit(new Millennium());
}
But this had a side effect of anything past "just now" showing as "1 day ago" instead of "today".
Anyone has an idea how to define this new rule for "today"? Thank you.
My test result of of "http://ocpsoft.org/prettytime/#section-2" code is :
moments from now
4 decades ago
not the second comment : //prints: “10 minutes from now” ,
add this "p=new PrettyTime(new Date(0));" before the seocnd println is right .
Using prettyTime version 3.2.5 on Android Studio.
Log.d(TAG, (new PrettyTime(new Locale("ZH_TW"))).format(new Date()));
and
Log.d(TAG, (new PrettyTime(new Locale("ZH_TW"))).format(new Date()));
do not display in Chinese (my system displays French instead);
PrettyTime dependency is added to the project in the build.gradle file:
compile 'org.ocpsoft.prettytime:prettytime:3.2.5.Final@jar'
It would be really great to be able to convert a date into text, especially time, so something like "ten past eleven" or "three o'clock". I could fork and implement this for english.
I couldn't find any. Thanks!
There's at least one expression that's inaccurate. "3 Months Ago" gets translated to "3 月 前" which should really be "3 ヶ月前". Here's an explanation:
"ヶ月" is used for representing a period of months in Japanese.
And only "月" is used for calender.
For example,
"3 ヶ月" means a period of three months.
And "3 月" means March.
I will be checking other expressions for accuracy and I plan to submit a PR with corrections.
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.
Your resources for Indonesian and Ukrainian refer to the language codes "in" and "ua". I am wondering if this really works in nowadays usage because the websites
http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
or
http://www.mathguide.de/info/tools/languagecode.html
list the codes "id" and "uk". Is this a problem for users of PrettyTime-library? Well, "in" seems to be an outdated variant, but "ua"???
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
Let's say today’s date is 1 March 2015 and I want to format 1 February 2015. Instead of getting month ago I get 28 days ago.
Hi!
Not sure if this is the right place for this.
The string used when translating "moments ago" to Spanish is wrong. The string used
"en un instante" should be "hace un instante".
"en un instante" means the opposite (that I will do something inmediatly, but in the future).
Best regards!
calculateDuration calls getUnits() twice and getUnits allocs new array etc. Could you update it to be faster and not alloc memory as often? Using on Android and this is showing up when profiling as slow. Using this in a scrolling list of views and it's laggy.
Please make PrettyTime available for Thymeleaf:
<p th:text="${#prettytime.format(date)}">1 year ago</p>
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()) + " тиж";
}
};
}
It seems that parsing "day before yesterday" returns "now". I walk around by passing "two days ago", but would be good to have it in there too.
I want to write time ago, like instagram does (the image above).
I have figured out how to shorten "2 weeks ago" into "2w". For that I have created a new class extending ListResourceBundle ( Resources_en_short
), and replaced "weeks", by "w".
I now have the following questions:
Resource_en_short
and not for other classes?I hope I am clear enough.
Thanks.
As far as I can see, this library only allows you to support dates/periods relative to now, like "3 months ago". Is there any way to use it for a generic period, like "3 months" (might refer to January to April last year)?
JodaTime supports this but not in a cool way. The nice thing about this library is that it prints only the bit you really care about, i.e. the most significant field. It doesn't say "3 months, 2 weeks, 5 days".
Here I asked for such a library on Stack Overflow but no-one could suggest anything: http://stackoverflow.com/questions/12579194/library-to-pretty-print-periods-of-time-in-java-giving-only-most-significant-fie. Do you know any such library?
If you don't have this support, would you be interested in including it?
Lib: prettytime-3.2.5.Final.jar
PrettyTime ptime = new PrettyTime();
List durations = ptime.calculatePreciseDuration(new Date(<some delta of 2 weeks ago>));
ptime.format(durations);
Actually Prints : <<<--- PRINTS "moments ago 2 weeks 3 hours 57 minutes"
Expected: "2 weeks 3 hours 57 minutes ago"
Creating 1000 PrettyTime objects takes 250 ms on my machine. It showed up as a bottleneck for our page.
Re-using the same Object and formatting 1000 dates takes only 12 ms, so a workaround would be to re-use the same PrettyTime object on each request or cache it for a short period.
Hi
I'm unable to use the prettytime-nlp lib in my very simple pom.xml
I always get the error:
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /Users/d023280/Documents/workspace/short-i/src/main/java/com/sap/twogo/shorti/test/PrettyDate.java:[11,23] cannot access org.ocpsoft.prettytime.natty.java.lang.Object
class file for org.ocpsoft.prettytime.natty.java.lang.Object not found
List dates = new PrettyTimeParser().parse("in three days!");
but as mention in hte documentation i just include the depency into my pom.xml.
any idea how to fix this?
Greetings
Andreas
Just a trivial issue, but the examples on http://ocpsoft.org/prettytime/ still use the 1.0.x package name like org.ocpsoft.pretty.time.PrettyTime
which has changed to org.ocpsoft.prettytime.PrettyTime
in 2.x.
Sorry, this is not really an issue, but i cant make it work, probably cause im a noob.
So i have a web application created in netbeans and there is no pom.xml cause is not a maven project.
What can i do to make it work? I alreaddy add a library with the jars clath, sources and doc) but the project dont find what is needed.
Thanks in advance
David
Hi - we are looking at PrettyTime for its use in an OpenNTF project. Did PretyTime used to be licensed under LGPL? If so - how did you manage the process of changing the license?
Thanks
Original issue: https://code.google.com/p/prettytime/issues/detail?id=17#makechanges
"On Android 3.2 / SDK r15 I'll get a missing resource exception for the Locale.German.
The ResourceBundle.getBundle tries to get a _de_de.xml resource, instead of a _de.xml resource."
Hi.
I think you should add initTimeUnits() in setLocale(final Locale locale) method. User change default locale and will still receive old time units.
I am in need to parse & get proper date format from some ill formatted date-time string. e.g. "04 Dec 2014 pm 1:58". When I do parse this example string, I get : "Thu Dec 04 02:59:33 ALMT 2014" which is I believe my current time stamp.
Can any of you kindly tell me, whether should I expect PrettyTime to parse for this type of ill-formatted string?
Btw, its a great library. Thanks so far. :)
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:
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
Hi
I would like to see a new version of this library as I would like to get the swedish translations working. It seems that there are some other localizations that would be nice to be released as well.
Regards
//Erik
I can't find the 4.0.0 version at http://search.maven.org/, the newest version is 3.2.7.
Why?
I currently searching for a library that can parse time strings like those created by PrettyTime, but I can't find anything useful.
It would be nice if PrettyTime also supported parsing
Getting the output "40 minutes 1 minute ago", when I really should get "40 minutes ago" or "41 minutes ago". Using the latest version (3.2.5.Final).
Here's my code (Scala):
val prettyTime = new PrettyTime();
prettyTime.clearUnits();
val minutes = new Minute();
prettyTime.registerUnit(minutes, new ResourcesTimeFormat(minutes));
System.out.println(prettyTime.format(prettyTime.calculatePreciseDuration(DateUtils.addSeconds(DateUtils.addMinutes(new Date(), -40), -10))));
I think the problem could be avoided by modifying the loop condition on line 225 from just checking for 0 equality to also checking whether the latest duration has the smallest unit - would that make sense? In other words, execute if duration.getDelta() != 0 or duration.getUnit().getClass() != units.keySet().iterator().next().getClass().
Thanks!
To make the normal prettytime jar a valid OSGi bundle, only a few headers must be added in the MANIFEST.MF file.
This is typically done automatically on build by using for example the maven-bundle-plugin (if you use maven for build). It can also be done post-build.
This would allow to use prettytime in an OSGi environment!
The JavaDoc for these methods states:
If {code then} is null, it will default to {code new Date()}
But the code throws an exception:
if (then == null)
throw new IllegalArgumentException("Date to format must not be null.");
The test expects the exception.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.