How to calculate elapsed time from now with Joda-Time?
To calculate the elapsed time with JodaTime, use Period
. To format the elapsed time in the desired human representation, use PeriodFormatter
which you can build by PeriodFormatterBuilder
.
Here's a kickoff example:
DateTime myBirthDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myBirthDate, now);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendSeconds().appendSuffix(" seconds ago\n")
.appendMinutes().appendSuffix(" minutes ago\n")
.appendHours().appendSuffix(" hours ago\n")
.appendDays().appendSuffix(" days ago\n")
.appendWeeks().appendSuffix(" weeks ago\n")
.appendMonths().appendSuffix(" months ago\n")
.appendYears().appendSuffix(" years ago\n")
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
System.out.println(elapsed);
This prints by now
3 seconds ago
51 minutes ago
7 hours ago
6 days ago
10 months ago
31 years ago
(Cough, old, cough) You see that I've taken months and years into account as well and configured it to omit the values when those are zero.
Joda Time: Calculate time to next full interval in month
Note: Check the following notice at the Home Page of Joda-Time
Joda-Time is the de facto standard date and time library for Java
prior to Java SE 8. Users are now asked to migrate to java.time
(JSR-310).
Therefore, I recommend you do it with the java.time
API using the following methods:
LocalDateTime#isBefore
LocalDateTime#plusWeeks
LocalDateTime#plusMonths
Using the java.time
API:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDateTime creation = createLocalDateTime("01.01.2021 06:30:00");
LocalDateTime due = createLocalDateTime("12.01.2021 05:30:00");
System.out.println(getNextWeeklyIntervalDate(creation, due, 1));
System.out.println(getNextMonthlyIntervalDate(creation, due, 1));
}
static LocalDateTime getNextWeeklyIntervalDate(LocalDateTime creationTime, LocalDateTime dueTime,
int intervalInWeeks) {
LocalDateTime ldt = creationTime;
while (ldt.isBefore(dueTime)) {
ldt = ldt.plusWeeks(intervalInWeeks);
}
return ldt;
}
static LocalDateTime getNextMonthlyIntervalDate(LocalDateTime creationTime, LocalDateTime dueTime,
int intervalInMonth) {
LocalDateTime ldt = creationTime;
while (ldt.isBefore(dueTime)) {
ldt = ldt.plusMonths(intervalInMonth);
}
return ldt;
}
static LocalDateTime createLocalDateTime(String dateTimeStr) {
return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss", Locale.ENGLISH));
}
}
Output:
2021-01-15T06:30
2021-02-01T06:30
These methods are available in Joda-time API as well i.e. all you need to change is the way how the date-time string is parsed and LocalDateTime
is obtained.
Using Joda-time API:
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime creation = createLocalDateTime("01.01.2021 06:30:00");
LocalDateTime due = createLocalDateTime("12.01.2021 05:30:00");
System.out.println(getNextWeeklyIntervalDate(creation, due, 1));
System.out.println(getNextMonthlyIntervalDate(creation, due, 1));
}
static LocalDateTime getNextWeeklyIntervalDate(LocalDateTime creationTime, LocalDateTime dueTime,
int intervalInWeeks) {
LocalDateTime ldt = creationTime;
while (ldt.isBefore(dueTime)) {
ldt = ldt.plusWeeks(intervalInWeeks);
}
return ldt;
}
static LocalDateTime getNextMonthlyIntervalDate(LocalDateTime creationTime, LocalDateTime dueTime,
int intervalInMonth) {
LocalDateTime ldt = creationTime;
while (ldt.isBefore(dueTime)) {
ldt = ldt.plusMonths(intervalInMonth);
}
return ldt;
}
static LocalDateTime createLocalDateTime(String dateTimeStr) {
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss");
LocalDateTime ldt = dtf.parseDateTime(dateTimeStr).toLocalDateTime();
return ldt;
}
}
Output:
2021-01-15T06:30:00.000
2021-02-01T06:30:00.000
As you can see, every thing, except the code inside createLocalDateTime
, is same for both java.time
and Joda-time API.
How do I measure time elapsed in Java?
Unfortunately, none of the ten answers posted so far are quite right.
If you are measuring elapsed time, and you want it to be correct, you must use System.nanoTime()
. You cannot use System.currentTimeMillis()
, unless you don't mind your result being wrong.
The purpose of nanoTime
is to measure elapsed time, and the purpose of currentTimeMillis
is to measure wall-clock time. You can't use the one for the other purpose. The reason is that no computer's clock is perfect; it always drifts and occasionally needs to be corrected. This correction might either happen manually, or in the case of most machines, there's a process that runs and continually issues small corrections to the system clock ("wall clock"). These tend to happen often. Another such correction happens whenever there is a leap second.
Since nanoTime
's purpose is to measure elapsed time, it is unaffected by any of these small corrections. It is what you want to use. Any timings currently underway with currentTimeMillis
will be off -- possibly even negative.
You may say, "this doesn't sound like it would ever really matter that much," to which I say, maybe not, but overall, isn't correct code just better than incorrect code? Besides, nanoTime
is shorter to type anyway.
Previously posted disclaimers about nanoTime
usually having only microsecond precision are valid. Also it can take more than a whole microsecond to invoke, depending on circumstances (as can the other one), so don't expect to time very very small intervals correctly.
Number of days between two dates in Joda-Time
Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.
// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
end.toLocalDate()).getDays());
// prints 1
Going via a LocalDate
sidesteps the whole issue.
Calculating the difference between two Java date instances
The JDK Date
API is horribly broken unfortunately. I recommend using Joda Time library.
Joda Time has a concept of time Interval:
Interval interval = new Interval(oldTime, new Instant());
EDIT: By the way, Joda has two concepts: Interval
for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration
that represents a length of time without the actual time boundaries (e.g. represent two hours!)
If you only care about time comparisions, most Date
implementations (including the JDK one) implements Comparable
interface which allows you to use the Comparable.compareTo()
How to find n'th previous Sunday with Java date time API or Joda-time?
You basically need to check if today is Sunday, if not, then look back for the previous one...(or recursively move back the date if you need the previous one to that...)
Using java 8 you will need:
DayOfWeek enumerator
TemporalAdjusters#previous
LocalDate date = LocalDate.now();
DayOfWeek todayAsDayOfWeek = date.getDayOfWeek();
LocalDate prevSun = todayAsDayOfWeek == DayOfWeek.SUNDAY ? date : date.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
System.out.println(prevSun);
Edit: previousOrSame method will skip the check of the actual dayof the week
LocalDate date = LocalDate.now();
LocalDate prevSun = date.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
prevSun = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
System.out.println(prevSun);
How can I calculate a time difference in Java?
String time1 = "16:00:00";
String time2 = "19:00:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
Difference is in milliseconds.
I modified sfaizs post.
Related Topics
What's the Advantage of a Java Enum Versus a Class with Public Static Final Fields
How to Calculate the Number of Rows (And Columns in Each Row) a Text Takes in a Jtextarea
Java Gui Frameworks. What to Choose? Swing, Swt, Awt, Swingx, Jgoodies, Javafx, Apache Pivot
Maven - Always Download Sources and Javadocs
Difference Between Spring @Controller and @Restcontroller Annotation
What Is a Difference Between <? Super E> and <? Extends E>
Get List of JSON Objects with Spring Resttemplate
Jdbc MySQL Connection Pooling Practices to Avoid Exhausted Connection Pool
Is It Bad to Explicitly Compare Against Boolean Constants E.G. If (B == False) in Java
Why Not to Start a Thread in the Constructor? How to Terminate
Java Date Parsing with Microsecond or Nanosecond Accuracy
Why Equals() Method When We Have == Operator
Why Were Applets Deprecated in Jdk 9
Java Annotations Values Provided in Dynamic Manner
What's the Difference Between Getpath(), Getabsolutepath(), and Getcanonicalpath() in Java