Date and Time Parsing and Formatting in Java with Joda Time

Posted 2008-12-04 in Java by Johann.

What's The Time? Ikea Clock

What's The Time? Ikea Clock by TomStardust, some rights reserved.

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
}

Subscribe

RSS 2.0, Atom or subscribe by Email.

Top Posts

  1. DynaCloud - a dynamic JavaScript tag/keyword cloud with jQuery
  2. 6 fast jQuery Tips: More basic Snippets
  3. xslt.js version 3.2 released
  4. xslt.js version 3.0 released XML XSLT now with jQuery plugin
  5. Forum Scanners - prevent forum abuse
  6. Automate JavaScript compression with YUI Compressor and /packer/

Navigation