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.
Related
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");
}
}
I am trying to find the difference between two java dates with time zone.
Time zone is GMT.Sever sends the time in this format 2015-04-08 11:17:53 -0400. I want to find the difference (in minutes)between server sent date format and current android system time.
I am finding the difference like this.c_date is the server date format(2015-04-08 11:17:53 -0400)
public static long getDiffrenceBetween(String c_date,String old_date) {
System.out.println("Cuttent Time :::"+c_date);
System.out.println("Saved/Old Time :::"+old_date);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Date d1 = null;
Date d2 = null;
long min_In_Minutes=0;
try {
d1 = format.parse(c_date);
d2 = format.parse(old_date);
// in milliseconds
long diff = d1.getTime() - d2.getTime();
min_In_Minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.println("Diff in Minutes :::"+min_In_Minutes);
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.println(diffDays + " days, ");
System.out.println(diffHours + " hours, ");
System.out.println(diffMinutes + " minutes, ");
System.out.println(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
return min_In_Minutes;
}
but this is giving negative value in minutes. what is wrong in this method. Please suggest.
Hoping that can find a solution here.
Thanks in advance,
sharath.
As you are using Android you obiosly cant use Java 8 and its new time api so I would reccomand using Joda-time - an external library for time.
Example for between calculation:
Seconds.between(startDate, endDate);
More details here: joda
GMT is the time anywhere in the world. GMT time code shows the difference between GMT and your local time. So theoretically ,
if your local time code is +/- "GMT 5.00"
difference between GMT and your local time = 5 * 60 minutes
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)));
I have an application, which needs to compare the time in seconds.
I want to know how to get the current UTC time in seconds.
Can some one post an example of it how can we do this in Java?
You can use this to get timezone passing in timezone you want time back in
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Then you can call whatever you want on the calendar object
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));
Below example to compare two calendars in seconds
Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// Set the dates for calendars
cal1.set(2011, 1, 1);
cal2.set(2011, 2, 2);
// Get the represented date in milliseconds as a long
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = milis2 - milis1;
// Calculate difference in seconds
long diffSecs = diff / 1000;
System.out.println("In seconds: " + diffSecs + " seconds");
System.currentTimeMillis()
public static long getUtcTime(long time) {
System.out.println("Time="+time);
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dbefore=new Date(time);
System.out.println("Date before conversion="+format.format(dbefore));
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
TimeZone timezone = c.getTimeZone();
int offset = timezone.getRawOffset();
if(timezone.inDaylightTime(new Date())){
offset = offset + timezone.getDSTSavings();
}
int offsetHrs = offset / 1000 / 60 / 60;
int offsetMins = offset / 1000 / 60 % 60;
System.out.println("offset: " + offsetHrs);
System.out.println("offset: " + offsetMins);
c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
c.add(Calendar.MINUTE, (-offsetMins));
System.out.println("Date after conversion: "+format.format(c.getTime()));
System.out.println("Time converted="+c.getTime().getTime());
return c.getTime().getTime();
}
Joda makes everything simple
import org.joda.time.ReadableInstant;
import org.joda.time.DateTime;
import static org.joda.time.DateTimeZone.UTC;
import static org.joda.time.Seconds.secondsBetween;
...
ReadableInstant start = new DateTime("2011-01-01", UTC);
ReadableInstant end = new DateTime("2011-02-02", UTC);
int secondsDifference = secondsBetween(start, end).getSeconds();
Get current UTC time in seconds (since 1.5) :
TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())
according to Javadoc:
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/System.html#currentTimeMillis
Returns:
the difference, measured in milliseconds, between the current time and
midnight, January 1, 1970 UTC.
To store the date as an integer instead of long, you can divide by 1000 and optionally subtract by another date, such as Jan. 1 2019:
private int getUTC()
{
Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal1.set(2019, 1, 1);
long millis1 = cal1.getTimeInMillis();
//Current date in milliseconds
long millis2 = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
// Calculate difference in seconds
long diff = millis2 - millis1;
return (int)(diff / 1000);
}
This works:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
GregorianCalendar gregorianCalendar = new GregorianCalendar
(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
calendar.get(Calendar.SECOND)
);
return gregorianCalendar.getTime();
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,