Formatting a Duration in Java 8 / jsr310

Java 9 and later: Duration::to…Part methods In Java 9 the Duration class gained new to…Part methods for returning the various parts of days, hours, minutes, seconds, milliseconds/nanoseconds. See this pre-release OpenJDK source code. Given a duration of 49H30M20.123S… toNanosPart() = 123000000 toMillisPart() = 123 toSecondsPart() = 20 toMinutesPart() = 30 toHoursPart() = 1 toDaysPart() = … Read more

Round minutes to ceiling using Java 8

The java.time API does not support rounding to ceiling, however it does support rounding to floor (truncation) which enables the desired behaviour (which isn’t exactly rounding to ceiling): LocalDateTime now = LocalDateTime.now(); LocalDateTime roundFloor = now.truncatedTo(ChronoUnit.MINUTES); LocalDateTime roundCeiling = now.truncatedTo(ChronoUnit.MINUTES).plusMinutes(1); In addition, there is a facility to obtain a clock that only ticks once a … Read more

How to check if a date Object equals yesterday?

Calendar c1 = Calendar.getInstance(); // today c1.add(Calendar.DAY_OF_YEAR, -1); // yesterday Calendar c2 = Calendar.getInstance(); c2.setTime(getDateFromLine(line)); // your date if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR)) { This will also work for dates like 1st of January.

java.time.format.DateTimeParseException: Text could not be parsed at index 3

First of all, check the javadoc. The uppercase D represents the day-of-year field (not the day-of-month as you want), and uppercase Y represents the week-based-year field (not the year as you want). The correct patterns are the lowercase letters d and y. Also, you’re using month names in uppercase letters (JAN and FEB), so your … Read more

Is Joda Time deprecated with java 8 Date and Time API? (java.time)

The official statement of the author of Joda-time himself is to migrate as soon as Java-8 is available. See also this citation from the website: Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310). So the short answer … Read more

Convert java.util.Date to what “java.time” type?

Yes, you definitely should be using the java.time framework whenever possible. Avoid old date-time classes The old date-time classes including java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat and such have proven to be poorly designed, confusing, and troublesome. Avoid them where you can. But when you must interoperate with these old types, you can convert between old and … Read more