Date Formatting and Parsing for Humans in Java with HumanTime
Posted 2008-10-07 in Java by Johann.
Many applications deal with time. For example by
- printing how long a task will take,
- logging timing information or
- letting users enter time intervals.
For a programmer, the system time in milliseconds is the fastest and easiest way to work with time.
The problem is that understanding and working with milliseconds is easy for computers, but not for humans.
HumanTime changes this.
HumanTime formats and parses time in a way that is easier to read and understand.
Examples
81299 ms
versus 1 m 21 s
1222940000 ms
versus 14 d 3 h
Which time representation is easier to understand?
Applications that do this well include Jenkins and Twitter:
Get HumanTime
Download HumanTime and the test case.
HumanTime has no dependencies besides Java 5. As usual, the code is released under the MIT License (OSI certified).
Using HumanTime
After downloading HumanTime, create a package called com.eaio.util.text
and put HumanTime.java
there. You’re done.
Formatting Time
There are two ways to display time in a human-readable format: An approximate and an exact representation. You should use the approximate representation unless you are sure the user is interested in the exact time.
// You’ve found that the job will take 56720083 milliseconds LOG.info("This job will take " + HumanTime.approximately(56720083L)); // Prints "This job will take 15 h 45 m"
An exactly
method is provided for the exact representation.
// You’ve found that the job will take 56720083 milliseconds LOG.info("This job will take exactly " + HumanTime.exactly(28391L)); // Prints "This job will take exactly 15 h 45 m 20 s 83 ms"
Parsing Time
HumanTime also parses time from user input. The input can contain the time symbols y
, d
, h
, s
and ms
. Whitespace is ignored, times are cumulative and parsing is case insensitive. An example:
HumanTime t = HumanTime.eval("29 m 30m 100 ms"); LOG.info(t.getApproximately()); // Will print "1 h" // Or simply use LOG.info(HumanTime.approximately("29 m 30m 100 ms"));
Other HumanTime Properties
HumanTime instances are thread-safe and can be serialized. In addition to the methods described above, HumanTime instances can also be created directly and modified through the d()
, d(int n)
, h()
, h(int n)
methods which add one day, n days, one hour and n hours respectively.
Summary
Working with time in a way that is easy for computers is not always easy to understand for humans. HumanTime makes time easier to read and understand.
4 comments
Java UUID generators compared
Posted 2007-04-25 in Java by Johann.
UUIDs (or GUIDs) are unique identifiers that are frequently used in programming. In this entry, I will compare three generators of UUIDs written in the Java programming language.
Possible uses for UUIDs
UUIDs have a variety of uses, including
- Temporary file names.
- Unique identifiers for website visitors.
- Transaction IDs.
- Primary keys, replacing database sequences.
Generally, whenever unique values across different machines are needed, UUIDs are a good choice.
The contestants
The following packages were compared:
- UUID – my own implementation.
- Java UUID Generator.
java.util.UUID
, available since JDK 5.
I did not compare the following packages:
- The implementation found in Jini.
- Commons Id – there is no release as of now.
The features
I compared the following features:
- Ease of use: How many lines of code does it take to get a UUID?
- Versions: The UUID versions supported (1–5).
- Speed: The performance of generating UUIDs.
- EJB: Whether the generated UUIDs can be used as primary keys in enterprise java beans.
- CORBA: Whether the generated UUIDs can be used in CORBA.
- Parse: Whether parsing UUIDs is supported. Usually, this is done from
java.lang.String
s, although JUG also supports parsing frombyte
arrays.
The results
Name |
Ease of use |
Versions |
Speed |
EJB |
CORBA |
Parse |
---|---|---|---|---|---|---|
++: very good, +: good, o: acceptable, -: bad, --: very bad |
||||||
UUID |
++ |
1 |
++ |
Yes |
Yes |
|
JUG |
o |
1, 3–5 |
+/-/-- |
No |
No |
|
JDK 5 |
++ |
3, 4 |
-/-- |
No |
No |
|
The benchmark
The performance of all generators was compared. The test computer was an Intel Pentium M 1.73 GHz computer with 1.5 GB of RAM. Load on the computer was low during the tests.
The following Java Virtual Machines were used:
- Sun JDK 1.5.0_05
- IBM 1.3.1
- Sun 1.4.2_09
- BEA JRockit 1.4.2_08
- BEA JRockit 1.5.0_08
- Sun JDK 6
All Java Virtual Machines were started with -Xms256M -Xmx256M
to force a fixed VM size.
The data
The following table contains the timings in milliseconds for the creation of one million UUIDs with the various implementations.
VM |
UUID |
JUG, time |
JUG, name |
JUG, random |
JDK, random |
JDK, name |
---|---|---|---|---|---|---|
Sun 1.5.0_05 |
1315 |
3424 |
25518 |
25946 |
28565 |
35253 |
IBM 1.3.1 |
2359 |
6796 |
81134 |
46584 |
||
Sun 1.4.2_09 |
2800 |
7053 |
91569 |
64956 |
||
JRockit 1.4.2_08 |
2556 |
5859 |
63890 |
47500 |
||
JRockit 1.5.0_08 |
1431 |
3756 |
25653 |
35093 |
35797 |
32253 |
Sun JDK 6 |
2303 |
5703 |
35968 |
41100 |
41553 |
48859 |
My own implementation is the fastest by a factor of at least two. With a modern computer, it is possible to generate more than 500.000 UUIDs per second.
The good
All of the implementations I tested generated unique UUIDs, even when used multi-threaded.
The bad
Some of the implementations are slower than others. It might not be possible to use some implementations in environments like EJB containers.
The MAC address issue
The computer’s MAC address must be encoded into a version 1 UUID. Because there is no official way in Java to do this, JUG comes with a native library (compiled for Windows x86, FreeBSD, Linux x86, MacOSX PPC, SPARC). My own version does this without native code (tested on Windows, Linux, MacOSX, BSDs, Solaris, HP-UX) and falls back to random data if the MAC address cannot be read.
Security aspects must be considered when version 1 UUIDs that contain the MAC address are made public.
The summary
If you need speed and/or support for EJBs or CORBA, UUID is the best way. If security is of ultimate importance to you, it cannot be used. In that case, JUG in the time-based mode is a good choice.
2 comments
Backup Twitter Tweets with TwitterBackup
Posted 2008-10-16 in Java by Johann.
Are you worried about losing your Twitter tweets? I too looked for a tool to back up my Twitter updates but couldn’t find one. So – I wrote one. And you can have it for free!
TwitterBackup
TwitterBackup is a tool that downloads all your tweets and stores them in XML format. The document type is identical to Twitter’s API.
Download
Download TwitterBackup 3.2.9 (779 KB) (last updated 2016-11-06)
Source code also available (6.4 MB).
After downloading, double-click the twitterbackup-3.2.9.jar
file. If this doesn’t work, open a command prompt and type java -jar twitterbackup-3.2.9.jar
.
Running TwitterBackup
This is TwitterBackup. Fill out the fields and press “Start.”
Username
Enter your Twitter user name here. Not your email address.
Password
Well, your password.
File Name
This is the name of the file where your tweets will be stored after they have been downloaded.
If the file exists, TwitterBackup will read it and add only newer tweets to it. This is an incremental backup and faster than a full backup.
Proxy
If you are connected to the internet through a proxy, enter the proxy address and the port (optional) here. Examples: blaproxy
, blaproxy:9080
.
Start
To download all Tweets, click this button. This will start the Twitter back up process.
Notes
- TwitterBackup might not work if you have blank characters in your password.
- License is MIT License (OSI certified).
- There is a delay time of several seconds between requests (as demanded by the Twitter API).
- Depending on the number of your updates, the backup process can take several minutes.
- Your settings are stored on your computer, not on my server or anywhere on the net.
20 comments
Date and Time Parsing and Formatting in Java with Joda Time
Posted 2008-12-04 in Java by Johann.
Joda Time is above all a replacement for the java.text.DateFormat
, java.text.SimpleDateFormat
and java.util.Calendar
classes. The original java.text
and java.util
classes are probably best known for not being thread-safe. In addition to being threadsafe, Joda Time also adds a richer and easier-to-use API.
This article is meant to be a cheat sheet for Joda Time – I will add more tips over time.
Date Parsing
The first line parses the Apache/lighttpd common or extended log file date format. The second one parses an ISO 8601 format.
DateTimeFormatter parser1 = DateTimeFormat.forPattern("dd/MMM/yyyy:HH:mm:ss Z"); DateTimeFormatter parser2 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"); DateTime time = parser1.parseDateTime("<data>");
Time Addition and Subtraction
Do something if a date is less than one month in the past from now.
DateTime time = getTimeFromSomewhere(); DateTime now = new DateTime(); if (time.plusMonths(1).isAfter(now)) { // something interesting happens here }
All methods you’d expect are there: plusDays
, plusHours
, plusMillis
, plusMinutes
, plusMonths
, plusSeconds
, plusWeeks
, plusYears and minusDays
, minusHours
, minusMillis
, minusMinutes
, minusMonths
, minusSeconds
, minusWeeks
and minusYears
. The API is chainable/fluent, so time.plusMonths(1).plusDays(1)
works.
Before/After
Easily done using isBefore
and isAfter
:
if (time.isAfter(agent.lastSeen)) { // computer reboots here }
Pages
Page 1 · Page 2 · Page 3 · Page 4 · Next Page »
Subscribe
RSS 2.0, Atom or subscribe by Email.
Top Posts
- DynaCloud - a dynamic JavaScript tag/keyword cloud with jQuery
- 6 fast jQuery Tips: More basic Snippets
- xslt.js version 3.2 released
- xslt.js version 3.0 released XML XSLT now with jQuery plugin
- Forum Scanners - prevent forum abuse
- Automate JavaScript compression with YUI Compressor and /packer/