How can I calculate a time span in Java and format the output?
Since everyone shouts "YOODAA!!!" but noone posts a concrete example, here's my contribution.
You could also do this with Joda-Time. Use Period
to represent a period. To format the period 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()
.appendYears().appendSuffix(" year, ", " years, ")
.appendMonths().appendSuffix(" month, ", " months, ")
.appendWeeks().appendSuffix(" week, ", " weeks, ")
.appendDays().appendSuffix(" day, ", " days, ")
.appendHours().appendSuffix(" hour, ", " hours, ")
.appendMinutes().appendSuffix(" minute, ", " minutes, ")
.appendSeconds().appendSuffix(" second", " seconds")
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
System.out.println(elapsed + " ago");
Much more clear and concise, isn't it?
This prints by now
32 years, 1 month, 1 week, 5 days, 6 hours, 56 minutes, 24 seconds ago
(Cough, old, cough)
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.
Is there an easy way to Calculate and format time/date intervals in java?
Have you tried Joda Time?
Calculate date/time difference in java
try
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
NOTE: this assumes that diff
is non-negative.
How to calculate relative time spans using Java (code converting problem)?
You need to gain a deeper understanding of what this method actually does. Literally translating code from C# to Java won't give you a good solution and gets you stuck on language-specific details.
The two lines basically calculate the (absolute) difference in seconds of a timestamp
to the current time. This can be written in Java as follows:
Duration duration = Duration.between(LocalDateTime.now(), timestamp);
long delta = duration.abs().getSeconds();
I'm just addressing your actual question here on how to transform these two lines. The provided snippet is not valid Java code and some parts are missing. delta
is the difference in seconds which does not necessarily need to be a double. The argument you pass to your method should be named anything else than now
because this is the timestamp you want to compare to the current time inside the method.
Calculate duration between two hours in Java
The basic flaw here is that you want the NEAREST distance between two times. When you are constructing your date objects, even though you only format for Hour:Minute:Second it still stores the day/month/year etc... For the dates 12:03:00 and 00:00:00 it defaults them to the same day, so the difference from (Midnight to Noon) is what your getting not (Noon to Midnight) of the next day. The solution for you would be to check if the times are less than 12 (military time) and if so add 1 to the day.
Here's How you do it:
String t1 = "12:03:00";
String t2 = "00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date d1 = sdf.parse(t1);
Date d2 = sdf.parse(t2);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
if(c2.get(Calendar.HOUR_OF_DAY) < 12) {
c2.set(Calendar.DAY_OF_YEAR, c2.get(Calendar.DAY_OF_YEAR) + 1);
}
long elapsed = c2.getTimeInMillis() - c1.getTimeInMillis();
How to calculate time ago in Java?
Take a look at the PrettyTime library.
It's quite simple to use:
import org.ocpsoft.prettytime.PrettyTime;
PrettyTime p = new PrettyTime();
System.out.println(p.format(new Date()));
// prints "moments ago"
You can also pass in a locale for internationalized messages:
PrettyTime p = new PrettyTime(new Locale("fr"));
System.out.println(p.format(new Date()));
// prints "à l'instant"
As noted in the comments, Android has this functionality built into the android.text.format.DateUtils
class.
Related Topics
How to Retrieve Value from Jtextfield in Java Swing
Difference Between List, List<>, List<T>, List<E>, and List<Object>
Are "While(True)" Loops So Bad
What Objects How to Inject Using the @Context Annotation
Java.Util.Zip.Zipexception: Error in Opening Zip File
Missing Return Statement for If/Else Statement
How to Asynchronously Call a Method in Java
Calling Outer Class Function from Inner Class
Java for Loop Syntax: "For (T Obj:Objects)"
How to Use Regex in String.Contains() Method in Java
How to Convert a String to Double in Java Using a Specific Locale
Is the Buildsessionfactory() Configuration Method Deprecated in Hibernate
Java Dynamic Binding and Method Overriding
The Meaning of Noinitialcontextexception Error
How to Fix Ambiguous Type on Method Reference (Tostring of an Integer)
Capturing Image from Webcam in Java
Best Way to Make Java's Modulus Behave Like It Should with Negative Numbers