In my code, I am generating timestamps value that is long millisecond .I want to convert this to HH:mm:ss(600000 to 00:10:00),I want disply difference in hh:mm:ss format
String strstart = "8:30:00";
String strend = "8:40:00";
SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm:ss");
try {
Date date1 = sdf1.parse(strstart);
Date date2 = sdf1.parse(strend);
long durationInMillis = date2.getTime() - date1.getTime();
System.out.println("durationInMillis---->" + durationInMillis);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I use bellow code and the output is 0:10:0 like this but i want the output like 00:10:00
int seconds = (int) (durationInMillis / 1000) % 60 ;
int minutes = (int) ((durationInMillis / (1000*60)) % 60);
int hours = (int) ((durationInMillis / (1000*60*60)) % 24);
System.out.println(hours+":"+minutes+":"+seconds);
System.out.printf("%02d:%02d:%02d%n", hours, minutes, seconds);
By the way, use "HH:mm:ss" as h is for the 12 hour format (AM/PM) and H for the 24 hour format - an interesting bug,
If you want to printf you can use the same as mentioned by Joop Eggen. If you want to store the same in another string you can use as below.
String output = String.format("%02d:%02d:%02d%n", hours, minutes, seconds);
Another solution:
sdf1.setTimeZone(TimeZone.getTimeZone("etc/UTC"));
System.out.println(sdf1.format(new Date(durationInMillis)));
Related
I want to get time difference between two times in milliseconds.
Note
If the difference is above half a second they return 1000 millisecond, so how to get
proper millisecond like if difference of half second to get 500 millisecond
Difference between two times is half second then my code returns
1000 milliseconds that means 1 Second but actually its 0.5 Second so how get 500
milliseconds if difference is half second
Date Date1 = sdf.parse(lastTime);
Date Date2 = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
long millie = Date2.getTime() - Date1.getTime();
SimpleDateFormat does not include milliseconds by default. So
sdf.format(Calendar.getInstance().getTime());
does not output the milliseconds and everything is rounded to seconds.
Define a custom date format including milliseconds like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ\"");
If you use java8 then try with this:
LocalDateTime startTime = LocalDateTime.of(2018,07,31,12,1);
long diff = ChronoUnit.MILLIS.between(startTime,LocalDateTime.now());
you can find difference between two date in millisecond,second,minutes and hours by calling following method, you can change method by your requirements.
public void printDifference(Date startDate) {
Date endDate=new Date();
long different = endDate.getTime() - startDate.getTime(); //Different in miliseconds
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
int months=0,year=0;
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
}
try my below code:
Date date = null;
String value="3 Feb 2018 13:01:41 GMT";
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
date = formatter.parse(value);
} catch (Exception e) {
e.printStackTrace();
}
// Prints the date in the CET timezone
System.out.println("ConvertTime from serverformat before settimezone ::" + formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getDefault());
// Prints the date in the IST timezone
System.out.println("ConvertTime from serverformat after settimezone ::" + formatter.format(date));
DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Date dateobj = new Date();
System.out.println("Current date and time before settimezone:: " + df.format(dateobj));
df.setTimeZone(TimeZone.getDefault());
System.out.println("current format after settimezone ::" + df.format(dateobj));
int difference = 0;
int diff_Minutes=0;
int diff_Seconds=0;
System.out.println("Default values::" + difference+" "+diff_Minutes+" "+diff_Seconds);
difference = (int) (dateobj.getTime() - date.getTime());
diff_Minutes = difference / (60 * 1000) % 60;
diff_Seconds = difference / 1000 % 60;
here i am converting current time from server time . here u have to take difference between two times. i hope you understand above code.let me know is it ok or not...
Thanks.
I am having java.sql.date and java.sql.time objects, I need to find the time duration between the dates.
So i am creating java.sql.timestamp object by using above date and time object
Timestamp timestamp1 = new Timestamp(StartDate.getYear(),
StartDate.getMonth(), StartDate.getDay(),
StartTime.getHours(), StartTime.getMinutes(), 00,
00);
Here is mycode
String date = "2010-01-05";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date3 = null;
try {
date3 = sdf1.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
Date StartDate = new Date(date3.getTime());
System.out.println("Date " + StartDate);
String date2 = "2010-01-06";
java.util.Date date4 = null;
try {
date4 = sdf1.parse(date2);
} catch (ParseException exception) {
exception.printStackTrace();
}
Date EndDate = new Date(date4.getTime());
System.out.println("Date " + EndDate);
String time = "01:00";
DateFormat formatter = new SimpleDateFormat("HH:mm");
java.sql.Time StartTime = null;
try {
StartTime = new java.sql.Time(formatter.parse(time).getTime());
} catch (ParseException exception2) {
exception2.printStackTrace();
}
System.out.println("TIMEEEEEEEEEE====" + StartTime);
String time2 = "02:00";
java.sql.Time EndTime = null;
try {
EndTime = new java.sql.Time(formatter.parse(time2).getTime());
} catch (ParseException exception3) {
exception3.printStackTrace();
}
System.out.println("TIMEEEEEEEEEE====" + EndTime);
Timestamp timestamp1 = new Timestamp(StartDate.getYear(),
StartDate.getMonth(), StartDate.getDay(),
StartTime.getHours(), StartTime.getMinutes(), 00,
00);
Timestamp timestamp2 = new Timestamp(EndDate.getYear(),
EndDate.getMonth(), EndDate.getDay(),
EndTime.getHours(), EndTime.getMinutes(), 00, 00);
long milliseconds = timestamp2.getTime() - timestamp1.getTime();
int seconds = (int) milliseconds / 1000;
// calculate hours minutes and seconds
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = (seconds % 3600) % 60;
System.out.println(hours+"h:"+minutes+"m:"+"00s");
Test case
when I give date as 2010-01-05 and date2 as 2010-01-06 I am getting output as below
Date 2010-01-05
Date 2010-01-06
TIMEEEEEEEEEE====01:00:00
TIMEEEEEEEEEE====02:00:00
25h:0m:00s
when I give date as 2010-01-05 and date2 as 2010-01-11 I am getting output in negative value as below
Date 2010-01-05
Date 2010-01-11
TIMEEEEEEEEEE====01:00:00
TIMEEEEEEEEEE====02:00:00
-23h:0m:00s
Help me to correct if I am doing something wrong.
Thanks in advance.
Manual time calculation:-
Converts Date in milliseconds (ms) and calculate the differences between two dates, with following rules :
1000 milliseconds = 1 second
60 seconds = 1 minute
60 minutes = 1 hour
24 hours = 1 day
Sample Example:-
package com.dps2.practice.dyuti;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDifferentExample {
public static void main(String[] args) {
String dateStart = "08/11/2016 09:29:58";
String dateStop = "08/12/2016 10:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem with your calculation is this: StartDate.getDay() etc.
getDay() will return the number of day of the week (read the JavaDoc) and not the day of the month. You'll need to use getDate() instead.
To illustrate the problem using your values: 2010-01-05 will return 2 for getDay() and thus you are getting 2010-01-02 as your timestamp. 2010-01-11 will return 1 for getDay() (it's 6 days later, i.e. (2 + 6) % 7 = 1) and hence your second timestamp becomes 2010-01-01. Now the second timestamp is before the first and hence you get a negative value.
However, as I already stated in my comments you should try and use some library or at least the non-deprecated built-in functionality for those calculations to save you a lot of headaches (I suggest you watch this video to get an idea of the challenges: https://youtube.com/watch?v=-5wpm-gesOY ).
The java.sql date-time classes are meant only for exchanging data with databases. Do not use them for business logic. Also, they are part of the troublesome, poorly designed, and confusing old legacy date-time classes. Avoid them all.
java.time
The java.time classes built into Java 8 and later supplant the old classes you are using. Much simpler now.
LocalDate ld = LocalDate.parse ( "2010-01-06" );
LocalTime lt = LocalTime.parse ( "01:00" );
LocalDateTime earlier = LocalDateTime.of ( ld , lt );
LocalDateTime later = earlier.plusHours ( 7 );
The Duration class represents a span of time as a total number of seconds and nanoseconds. Its toString method generates a String in the standard ISO 8601 format PnYnMnDTnHnMnS. This format uses P to mark the beginning, and the T to separate year-months-days from hours-minutes-seconds portion. The Duration and Period classes can both parse and generate such Strings.
Duration duration = Duration.between ( earlier , later );
In Java 8, Duration class inexplicably lacks getter methods for each part: days, hours, minutes, seconds, fraction-of-second. Java 9 rectifies this omission with new getPart methods.
Dump to console.
System.out.println ( "earlier: " + earlier + " | later: " + later + " | duration: " + duration );
earlier: 2010-01-06T01:00 | later: 2010-01-06T08:00 | duration: PT7H
Time zone
Be aware that your inputs lacked any information about offset-from-UTC or time zone. So the math seen above is performed assuming generic 24-hour days. Real-world anomalies such as Daylight Saving Time (DST) are ignored.
If you did indeed intend time zones, assign them via the atZone method to instantiate OffsetDateTime or ZonedDateTime objects.
That's a complicated code you have in your question there. You can make it quite easy by using java.util.concurrent.TimeUnit class.
Output
Date Tue Jan 05 00:00:00 UTC 2010
Date Wed Jan 06 00:00:00 UTC 2010
difference is:
24 hours : 1440 minutes : 86400 seconds
Code
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
public class HelloWorld {
public static void main(String[] args) {
String date = "2010-01-05";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date3 = null;
try {
date3 = sdf1.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
Date StartDate = new Date(date3.getTime());
System.out.println("Date " + StartDate);
String date2 = "2010-01-06";
java.util.Date date4 = null;
try {
date4 = sdf1.parse(date2);
} catch (Exception exception) {
exception.printStackTrace();
}
Date EndDate = new Date(date4.getTime());
System.out.println("Date " + EndDate);
long dateStart = StartDate.getTime(), dateStop = EndDate.getTime();
long diff = dateStop - dateStart;
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(diff);
long diffInHours = TimeUnit.MILLISECONDS.toHours(diff);
System.out.println("\n\ndifference is:\n");
System.out.println(diffInHours + " hours : " + diffInMinutes + " minutes : " + diffInSeconds + " seconds");
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculating the Difference Between Two Java Date Instances
i have two date values in two textboxes in string datatypes in HH:MM:SS format.HOw can i find difference between them and get result in HH:MM:SS?please help me...as fast as possible....!
Try this:
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date date1 = (Date) format.parse("4:15:20");
Date date2 = (Date) format.parse("2:30:30");
//time difference in milliseconds
long timeDiff = date1.getTime() - date2.getTime();
//new date object with time difference
Date diffDate = new Date(timeDiff);
//formatted date string
String timeDiffString = format.format(diffDate);
System.out.println("Time Diff = "+ timeDiffString );
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Above code has certain limitations. Other proper way could be to convert the long value of time difference manually in the string as below:
long timeDiffSecs = timeDiff/1000;
String timeDiffString = timeDiffSecs/3600+":"+
(timeDiffSecs%3600)/60+":"+
(timeDiffSecs%3600)%60;
System.out.println("Time Diff = "+ timeDiffString);
The code you have will give you the number of milliseconds difference between the listed dates. It could be that the answer could be simply divide by 1000 to get the number of seconds.
First Convert String date into simple Date formate
public String getconvertdate1(String date)
{
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
Date parsed = new Date();
try
{
parsed = inputFormat.parse(date);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String outputText = outputFormat.format(parsed);
return outputText;
}
//now can do anything with date.
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);// you get day difference between
AND use simpledateFormate to configure HH:MM:SS
I have a method which uses following logic to calculate difference between days.
long diff = milliseconds2 - milliseconds1;
long diffDays = diff / (24 * 60 * 60 * 1000);
but I want for ex, 9th feb 2011 to 19th feb 2011 should return me 11 days irrespective of second or milliseconds consideration. How can I achieve this?
For the groovy solution you asked for you should consider using this:
use(groovy.time.TimeCategory) {
def duration = date1 - date2
println "days: ${duration.days}, Hours: ${duration.hours}"
}
It's very easy to understand and extremely readable. You asked for a example how this can be used in an easy method which calculates the days between two dates. So here is your example.
class Example {
public static void main(String[] args) {
def lastWeek = new Date() - 7;
def today = new Date()
println daysBetween(lastWeek, today)
}
static def daysBetween(def startDate, def endDate) {
use(groovy.time.TimeCategory) {
def duration = endDate - startDate
return duration.days
}
}
}
If you run this example it will print you 7. You can also enhance this method by using before() and after() to enable inverted dates.
It's a well worn line, but for Dates use JodaTime.
Here's how to calculate date intervals using JodaTime.
Days days = Days.daysBetween(new DateTime(millis1), new DateTime(millis2));
int daysBetweenDates = days.getDays();
In groovy all you need is:
date2 - date1
which returns an integer representing the number of days between the two dates.
Or if you need to guard against reversal of order between the two Date instances (the operation returns negative numbers when the first operand is earlier than the second):
Math.abs(date2 - date1)
The above examples use the groovy date.minus(date) operator implementation which returns the number of days between the two dates.
Example groovy shell session:
$ groovysh
Groovy Shell (2.4.8, JVM: 1.8.0_111)
Type ':help' or ':h' for help.
groovy:000> x = new Date(1486382537168)
===> Mon Feb 06 13:02:17 CET 2017
groovy:000> y = new Date(1486000000000)
===> Thu Feb 02 02:46:40 CET 2017
groovy:000> x - y
===> 4
or if you need a method:
int daysBetween(date1, date2) {
Math.abs(date2 - date1)
}
GregorianCalendar cal1 = new GregorianCalendar(2011,2,9);
GregorianCalendar cal2 = new GregorianCalendar(2011,2,19);
long ms1 = cal1.getTime().getTime();
long ms2 = cal2.getTime().getTime();
long difMs = ms2-ms1;
long msPerDay = 1000*60*60*24;
double days = difMs / msPerDay;
just parse 9th feb 2011 & 19th feb 2011 into dates using SimpleDateFormat and convert it to start & end millis and apply your calculation
Try this:
DateFormat format = DateFormat.getDateTimeInstance();
Date completeDate=null;
Date postedDate=null;
try
{
completeDate = format.parse("18-May-09 11:30:57");
postedDate = format.parse("11-May-09 10:46:37");
long res = completeDate.getTime() - postedDate.getTime();
System.out.println("postedDate: " + postedDate);
System.out.println("completeDate: " + completeDate);
System.out.println("result: " + res + '\n' + "minutes: " + (double) res / (60*1000) + '\n'
+ "hours: " + (double) res / (60*60*1000) + '\n' + "days: " + (double) res / (24*60*60*1000));
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
If you want days to be an integer then just remove casting to double.
HTH
This assumes times are in UTC or GMT.
long day1 = milliseconds1/ (24 * 60 * 60 * 1000);
long day2 = milliseconds2/ (24 * 60 * 60 * 1000);
// the difference plus one to be inclusive of all days
long intervalDays = day2 - day1 + 1;
Date.metaClass.calculateDays = { Date offset = new Date() ->
Long result = null
Date date = delegate
use(groovy.time.TimeCategory) {
result = (offset - date).days as Long
}
result
}
example of use:
def sdf = new java.text.SimpleDateFormat("yyyy.MM.dd")
sdf.lenient = false
Date date = sdf.parse("2015.10.02")
println date.calculateDays()
println date.calculateDays(sdf.parse("2015.11.02"))
Find out the number of days in between two given dates:
#Test
public class Demo3 {
public static void main(String[] args) {
String dateStr ="2008-1-1 1:21:28";
String dateStr2 = "2010-1-2 1:21:28";
SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
SimpleDateFormat format2 = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
try {
Date date2 = format.parse(dateStr2);
Date date = format.parse(dateStr);
System.out.println("distance is :"+differentDaysByMillisecond(date,date2));
}catch(ParseException e ){
e.printStackTrace();
}
}
//get Days method
private static int differentDaysByMillisecond(Date date, Date date2) {
return (int)((date2.getTime()-date.getTime())/1000/60/60/24);
}
}
I have two Date objects and I need to get the time difference so I can determine the total hours between them. They happen to be from the same day. The result I would like would have the hours and minutes.
When I use .toString() on my Date object I get this: Fri Dec 18 08:08:10 CST 2009
I've tried the following:
long diff = (this.endDate.getTime() - this.startDate.getTime()) / (60 * 60 * 1000);
But this only gives me hours, not the minutes.
I know this is a simple problem, but I can't figure it out atm.
Edits:
Final solution for those interested. Thanks to Michael Brewer-Davis
Period p = new Period(this.startDate, this.endDate);
long hours = p.getHours();
long minutes = p.getMinutes();
String format = String.format("%%0%dd", 2);
return Long.toString(hours) + ":" + String.format(format, minutes);
This should work.
long secs = (this.endDate.getTime() - this.startDate.getTime()) / 1000;
int hours = secs / 3600;
secs = secs % 3600;
int mins = secs / 60;
secs = secs % 60;
Here's how it works with Joda time:
DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
int hours = p.getHours();
int minutes = p.getMinutes();
You could format with Joda's formatters, e.g., PeriodFormat, but I'd suggest using Java's. See this question for more details.
EDIT: be careful using this method to check hours between. This function don't respect days between. It get just hours between two times. 2022-07-20 11.00 and 2022-07-21 12.00 will return 1 hour, not 25 hours.
Here's simple way:
private static int hoursDifference(Date date1, Date date2) {
final int MILLI_TO_HOUR = 1000 * 60 * 60;
return (int) (date1.getTime() - date2.getTime()) / MILLI_TO_HOUR;
}
java.time.Duration
I should like to contribute the modern (java 8+) answer. The solutions using Joda-Time are fine. The Joda-Time project is in maintenance mode, so for new code we should not use it. I follow the official recommendation from the Joda-Time project and use java.time, the modern Java date and time API:
Duration dur = Duration.between(startDate, endDate);
String result = String.format("%d:%02d", dur.toHours(), dur.toMinutesPart());
System.out.println(result);
This works if startDate and endDate both have type Instant or OffsetDateTime or ZonedDateTime or LocalDateTime or LocalTime. All of the mentioned types are from java.time package. If starting with LocalDate, call either of the atStartOfDay methods.
The toMinutesPart methof was introduced in Java 9. If you are using Java 8 (ot ThreeTen Backport), search for java format duration or similar to learn how to format the duration into hours and minutes.
Two quotes from the Joda-Time home page:
Users are now asked to migrate to java.time (JSR-310).
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).
Links
Oracle tutorial: Date Time explaining how to use java.time.
Joda-Time home page
Please follow Somaiah's suggestion in a comment, use Hours instead:
Hours hours = Hours.hoursBetween(startTime, endTime);
The call to getHours() will only return the hour section of the time difference and ignore all year, month differences so it would not be correct in some cases.
If you use Period.toStandardHours() to try to convert the time difference into hours the calculation will throw an exception if the time difference between the two dates includes difference in either year or month, since the length of month is unknown.
So the getTime() method, I presume, returns an integer.
In which case, the left set of parentheses has type int, right?
and
(60*60*1000)
is also an int.
Which means you get long diff = ((int)/(int)) so the integer division is done BEFORE you cast stuff to long. And hence you lose your minutes.
Try casting them BEFORE you divide.
for kotlin, you can use below function and get hours between two date
private val dateFormat: String = "yyyy-MM-dd # hh:mm a"
val startDate = SimpleDateFormat(dateFormat).parse("2018-10-01 # 12:33 PM")
val endDate = SimpleDateFormat(dateFormat).parse("2018-10-01 # 02:46 PM")
private fun hoursDifference(date1: Date, date2: Date): Int {
val milliToHour : Long = 1000 * 60 * 60
return ((date1.time - date2.time) / milliToHour).toInt()
}
println(hoursDifference(endDate,startDate).toString())
Output:
2
Even though there's already an accepted answer, this is what worked for me using the Joda time library.
/**
*
* #param date1
* #param date2
* #return hours between two dates rounded down
*/
public static int hoursBetween(DateTime date1, DateTime date2) {
if(date1 == null || date2 == null) return NOT_FOUND;
return Math.abs(Hours.hoursBetween(date1.toLocalDateTime(), date2.toLocalDateTime()).getHours());
}
private void getHours(Date d1, Date d2){
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffDays = diff / (24 * 60 * 60 * 1000);
long diffHours = diff / (60 * 60 * 1000) % 24;
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.\n");
}`
//Displays:
/* 1 days, 1 hours, 1 minutes, 50 seconds. */
Here's a pure Java 8+ solution that does not involve Joda or mathematical operations
import java.time.*;
import java.time.temporal.*;
// given two java.util.Dates
Date startDate ...
Date endDate ...
// convert them to ZonedDateTime instances
ZonedDateTime start = ZonedDateTime.ofInstant(startDate.toInstant(), ZoneId.systemDefault());
ZonedDateTime end = ZonedDateTime.ofInstant(endDate.toInstant(), ZoneId.systemDefault());
// get the total duration of minutes between them
Duration total = Duration.ofMinutes(ChronoUnit.MINUTES.between(start, end));
// use the duration to determine the hours and minutes values
long hours = total.toHours();
long minutes = total.minusHours(hours).toMinutes();
Here is the simple method :-
Check your Date format,if your date not in this format then change it and pass to this method it will give you a String which is your result. Modify the method as per the requirement.
private String getDateAsTime(String datePrev) {
String daysAsTime = "";
long day = 0, diff = 0;
String outputPattern = "yyyy:MM:dd HH:mm:ss";
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Calendar c = Calendar.getInstance();
String dateCurrent = outputFormat.format(c.getTime());
try {
Date date1 = outputFormat.parse(datePrev);
Date date2 = outputFormat.parse(dateCurrent);
diff = date2.getTime() - date1.getTime();
day = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
} catch (ParseException e) {
e.printStackTrace();
}
if (day == 0) {
long hour = TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);
if (hour == 0)
daysAsTime = String.valueOf(TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS)).concat(" minutes ago");
else
daysAsTime = String.valueOf(hour).concat(" hours ago");
} else {
daysAsTime = String.valueOf(day).concat(" days ago");
}
return daysAsTime;
}
Hope this will help,