I want to calc the time differnce from when the user pressed start and stop.
This is what I got so far:
Done in not worker thread:
runTime = System.currentTimeMillis();
Done on main thread:
DateFormat formatter = new SimpleDateFormat("hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis() - runTime);
timeTextView.setText("Time: " + formatter.format(calendar.getTime()));
The result is always "01:00:00.000".
How come I get a 1hour added to the time?
And ofc I press the start and stop button faster then one hour.
The result you have is the time since epoch in java, So if you try to print
timeTextView.setText("Time: " + calendar.getTime().toString());
You are more likely to have the result of Wed Dec 31 19:00:00 EST 1969 depends on which TimeZone you currently are. From your code above I got 07:00:00:000 because I am at EST TimeZone. You cant really do about it but it eliminate the hh so it will only show the minutes, seconds, and milliseconds.
A simple way of solving (working around ?) this issue:
long startTime = System.currentTimeMillis();
//* do something
long endTime = System.currentTimeMillis();
long elapsedTimeInMilliSecs=(endTime - startTime);
Calendar ...
I use something like this and it works fine.
Try this if you just want your elapsed time in HH:MM:SS, this works even if you have more than 24 hours.
timeTextView.setText("Time: " + convertMillis(System.currentTimeMillis() - runTime));
...
public static String convertMillis(long milliseconds){
long time = milliseconds / 1000;
String seconds = Integer.toString((int)(time % 60));
String minutes = Integer.toString((int)((time % 3600) / 60));
String hours = Integer.toString((int)(time / 3600));
for (int i = 0; i < 2; i++) {
if (seconds.length() < 2) {
seconds = "0" + seconds;
}
if (minutes.length() < 2) {
minutes = "0" + minutes;
}
if (hours.length() < 2) {
hours = "0" + hours;
}
}
return(hours + ":" + minutes + ":" + seconds);
}
Related
How to get difference between two dates in Days, Hours (24), Minutes (60), Seconds(60).
and
I have been go through
Android difference between Two Dates
How do I get difference between two dates in android?, tried every thing and post
but no help,
Here is my code..
try {
String FinalDate = "20-04-2018 08:00:00";
String CurrentDate = "26-04-2018 10:10:30";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
/*long difference = date1.getTime() - date2.getTime();
long differenceInMinutes = difference / (60 * 1000);
long differenceInSeconds = difference / 1000;
String strMinuteDifference = Long.toString(differenceInMinutes);
String strSecondsDifference = Long.toString(differenceInSeconds);*/
long difference = date1.getTime() - date2.getTime();
long seconds = difference / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
Log.e("TAG_5", "CurrentDate is : " + date1);
Log.e("TAG_5", "Final date is : " + date2);
Log.e("TAG_5", "Day Difference: " + days);
Log.e("TAG_5", "hours Difference: " + hours);
Log.e("TAG_5", "Minute Difference: " + minutes);
Log.e("TAG_5", "Seconds Difference: " + seconds);
} catch (Exception exception) {
Log.e("TAG_5", "exception " + exception);
}
and the output is
E/TAG_5: CurrentDate is : Thu Apr 26 10:10:30 GMT+05:30 2018
E/TAG_5: Demo date is : Fri Apr 20 08:00:00 GMT+05:30 2018
E/TAG_5: Day Difference: 6
E/TAG_5: hours Difference: 146
E/TAG_5: Minute Difference: 8770
E/TAG_5: Seconds Difference: 526230
Its seems be like the code is Calculate All the Hours, Minutes, Seconds between those two dates but
I want Output be like...
Hours should be like 2 hours, 10 hours or 23 hours but not more than 24, because 25 hours will be new day so that should be 1 Day and 1 hour.
and Minutes be like 10 minutes 35 minutes or 59 minutes, but not more than 60
same goes for Seconds, it should be 12 seconds, 40 seconds or 59 seconds but not more than 60.
So how can i achieve this ?
To calculate the "rest" hours like you said. (So below 24 hours) you can use modulo.
In computing, the modulo operation finds the remainder after division
of one number by another (sometimes called modulus).
int hours = theAmountOfHours % 24
In your example
Log.e("TAG_5", "Day Difference: " + days);
Log.e("TAG_5", "hours Difference: " + hours % 24);
Log.e("TAG_5", "Minute Difference: " + minutes % 60);
Log.e("TAG_5", "Seconds Difference: " + seconds % 60);
Sources: Wikipedia
Try this method
public void printDifferenceDateForHours(Date startDate, Date endDate) {
//milliseconds
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
//TODO Here you will get the days
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
//TODO Here you will get the hours
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
//TODO Here you will get the minute
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
//TODO Here you will get the second
long elapsedSeconds = different / secondsInMilli;
}
try {
String FinalDate = "20-04-2018 08:00:00";
String CurrentDate = "26-04-2018 10:10:30";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
long seconds = 1000;
long minutes = 60 * seconds;
long hours = 60 * minutes;
long days = 24 * hours;
long weeks = 7 * days;
long months = 30 * days;
long year = 365 * days;
long difference = date1.getTime() - date2.getTime();
long differenceInDays = difference / days;
difference = difference - (differenceInDays * days);
long differenceInHours = (difference) / hours;
difference = difference - (differenceInHours * hours);
long differenceInMin = (difference) / minutes;
difference = difference - (differenceInMin * minutes);
long differenceInSecond = difference / seconds;
Log.e("TAG_5", "CurrentDate is : " + date1);
Log.e("TAG_5", "Final date is : " + date2);
Log.e("TAG_5", "Day Difference: " + differenceInDays);
Log.e("TAG_5", "hours Difference: " + differenceInHours);
Log.e("TAG_5", "Minute Difference: " + differenceInMin);
Log.e("TAG_5", "Seconds Difference: " + differenceInSecond);
} catch (Exception exception) {
Log.e("TAG_5", "exception " + exception);
}
Here i have calculated only day,month,min,second you can calculate year,month,week same way
You can use epoch time (unix timestamp) of both the dates and calculate the days, hours, mins and sms difference yourself using the modulo (% - remainder) operator.
You can do this way, I hope it help for you. thanks
String CurrentDate = "26-04-2018 10:10:30";
String FinalDate = "20-04-2018 08:00:00";
long diffInMillisec = CurrentDate.getTime() - FinalDate.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);
seconds = diffInSec % 60;
diffInSec/= 60;
minutes =diffInSec % 60;
diffInSec /= 60;
hours = diffInSec % 24;
diffInSec /= 24;
days = diffInSec;`
1.Divide the difference by days to get number of days/hours/minutes/etc.
2.perform Modulo to get the remaining seconds.
Use
long difference="your difference result here";
long seconds =1000;
long minutes =60*seconds;
long hours = 60*minutes;
long days = 24*hours;
long weeks=7*days;
long months=30*days;
long year=365*days;
if(difference>year) {
Log.d("year", String.valueOf(difference / year));
difference = difference % year;
}
if(difference>months) {
Log.d("months", String.valueOf(difference / months));
difference = difference % months;
}
if(difference>weeks) {
Log.d("weeks", String.valueOf(difference / weeks));
difference = difference % weeks;
}
if(difference>days) {
Log.d("days", String.valueOf(difference / days));
difference = difference % days;
}
if(difference>hours) {
Log.d("hours", String.valueOf(difference / hours));
difference = difference % hours;
}
if(difference>minutes) {
Log.d("minutes", String.valueOf(difference / minutes));
difference = difference % minutes;
}
if(difference>0)
Log.d("seconds", String.valueOf(difference/seconds ));
Hi i need to convert milliseconds (1437790538 its 25 july 2015) to seconds but when i trying to convert seconds then it not work i get irrelevant result.From last two days very stressed from these result.
i have use this code for doing this purpose
long duration_seconds = 1437790538;
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(duration_seconds * 1000);
calendar.add(Calendar.MILLISECOND,
tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currenTimeZone = (Date) calendar.getTime();
String resultabc = sdf.format(currenTimeZone);
long curMillis = currenTimeZone.getTime() / 1000;
// long seconds = (curMillis/ 1000) % 60;
Log.e("test", "datee1 :" + resultabc + " , " + curMillis + " , " + seconds);
getDurationBreakdown(curMillis);
calculateTime(seconds);
after i need to calculate total time of post like this
public static void calculateTime(long seconds) {
int day1 = (int) TimeUnit.SECONDS.toDays(seconds);
long hours1 = TimeUnit.SECONDS.toHours(seconds) - (day1 * 24);
long minute1 = TimeUnit.SECONDS.toMinutes(seconds)
- (TimeUnit.SECONDS.toHours(seconds) * 60);
long second1 = TimeUnit.SECONDS.toSeconds(seconds)
- (TimeUnit.SECONDS.toMinutes(seconds) * 60);
Log.e("test", "time interval ::" + "Day " + day1 + " Hour " + hours1
+ " Minute " + minute1 + " Seconds " + second1);
// int days, hours, mins, seconds, justnow;
days = (int) day1;
hours = (int) hours1;
mins = (int) minute1;
seconds = (int) second1;
System.out.println("Day " + day1 + " Hour " + hours1 + " Minute1 "
+ minute1 + " Seconds " + second1);
public static String getDurationBreakdown(long millis)
{
if(millis < 0)
{
throw new IllegalArgumentException("Duration must be greater than zero!");
}
long days = TimeUnit.MILLISECONDS.toDays(millis);
millis -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
millis -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
StringBuilder sb = new StringBuilder(64);
sb.append(days);
sb.append(" Days ");
sb.append(hours);
sb.append(" Hours ");
sb.append(minutes);
sb.append(" Minutes ");
sb.append(seconds);
sb.append(" Seconds");
Log.e("test", "time interval" + sb.toString());
return(sb.toString());
}
}
both methods giving wrong result.
if anybody have idea how to do this thing in correct way please help me out this problem..
thanks in advance
Your
long curMillis = currenTimeZone.getTime() / 1000;
seems misleading. .getTime() will give you the time in millis, so dividing it by 1000 you will get secs not milis...
UPDATE
As far as I understand your code you simply want to calculate the difference between a given date (represented in secs) and the actual date. For that you can just do
long myDateInSecs = 1437790538; // 25 july 2015
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(myDateInSecs * 1000);
Calendar calendarNow = Calendar.getInstance();
long diff = calendarNow.getTime() - calendar.getTime();
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
...
seconds % 60
1437790538 % 60 -> 38
1437790538 is a timestamp in seconds, not in milliseconds.
I am given a unix timestamp and I need to find the difference of seconds/min/hour by comparing with current time. I need something like:
34 sec ago
1 min ago
4 mins ago
5 hours ago
1 days ago
2 days ago
I have tried some poor if-else styled code but it is giving wrong wierd output
String time = null;
long quantity = 0;
long addition = 0;
long diffMSec = System.currentTimeMillis() - Long.parseLong(submissionInfo
.get(CommonUtils.KEY_SUBMISSION_TIME)) * 1000L;
diffMSec /= 1000L;
if (diffMSec < 86400L) { // less than one day
if (diffMSec < 3600L) { // less than one hour
if (diffMSec < 60L) { // less than one minute
quantity = diffMSec;
time = "sec ago";
} else { // greater than or equal to one minute
addition = (diffMSec % 60L) > 0 ? 1 : 0;
quantity = (diffMSec / 60L) + addition;
if (quantity > 1)
time = "mins ago";
else
time = "min ago";
}
} else { // greater than or equal to one hour
addition = (diffMSec % 3600L) > 0 ? 1 : 0;
quantity = (diffMSec / 3600L) + addition;
if (quantity > 1)
time = "hours ago";
else
time = "hour ago";
}
} else { // greater than or equal to one day
addition = (diffMSec % 86400) > 0 ? 1 : 0;
quantity = (diffMSec / 86400) + addition;
if (quantity > 1)
time = "days ago";
else
time = "1 day ago";
}
time = quantity + " " + time;
I need some working code with smarter approach or even any approach with working solution. Help me to figure it out.
I think you should use Calendar
Calendar cal = Calendar.getInstance();
String time = "yourtimestamp";
long timestampLong = Long.parseLong(time)*1000;
Date d = new Date(timestampLong);
Calendar c = Calendar.getInstance();
c.setTime(d);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
Calendar implements Comparable so ...
long subs = Math.abs(cal.getTimeInMillis() c.getTimeInMillis());
Calendar subCalendar = (Calendar)cal.clone();
subCalendar.setTimeInMillis(subs);
You can also use this link, because it seems to be a problem like yours
So [DateUtils.getRelativeTimeSpanString()][1] in the Android SDK works great for showing relative times that are in the past.
i.e: 5 days ago, or 5 minutes ago.
But doesn't seem to work so well for dates that are in the future. It seems to just print the date.
Are there any easy alternatives for generating relative time span strings for dates that are in the future (short of writing something that figures out the days, hours, minutes, seconds by comparing two calendar objects)?
Something a long the lines of: in 5 days, or in 5 minutes?
Here is basically what I would have to make, and it just looks kind of dirty (note: this code was written just for the post and not actually run through a java compiler):
Calendar calendarIO = Calendar.getInstance();
calendarIO.set(2013, 2, 14, 7, 0);
long milliseconds1 = calendarIO.getTimeInMillis();
long milliseconds2 = System.currentTimeMillis();
long diff = milliseconds1 - milliseconds2;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
String relativeTime = "";
if (diffDays > 1) {
relativeTime = diffDays + " days";
} else if (diffDays > 0) {
relativeTime = diffDays + " days " + diffHours + " hours";
} else if (diffHours > 1) {
relativeTime = diffHours + " hours";
} else if (diffMinutes > 0) {
relativeTime = diffMinutes + " minutes.";
}
I'd try using DateUtils.getRelativeTimeSpanString(time, now, minResolution) as it works for future dates using an "in n days" format.
http://developer.android.com/reference/android/text/format/DateUtils.html#getRelativeTimeSpanString
Follow following steps
String dateString = "06/05/2019 06:49:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
long cuMillis = System.currentTimeMillis();
String timeAgo = (String) DateUtils.getRelativeTimeSpanString(convertedDate.getTime(), cuMillis, 1, FORMAT_ABBREV_RELATIVE);
Log.d("LOG", "Time Ago==>" + timeAgo);
} catch (ParseException e) {
e.printStackTrace();
}
DateUtils.getRelativeTimeSpanString(endDate.getTime(), startDate.getTime(), DateUtils.FORMAT_ABBREV_RELATIVE);
With the following caveat:
Gives tomorrow instead of in 1 day.
I've got a String of a date/time in ISO-8601 format, like: 2011-04-15T20:08:18Z
I want to format this to a more readable date/time and then also be able to compare that later to the phone's local time. I'm a bit confused about what's been deprecated and what hasn't.
Do I need to use a Calendar object?
Can someone walk me through how to do this?
following is a code snippet you can use
StringBuffer sbDate = new StringBuffer();
sbDate.append(cDate);
String newDate = sbDate.substring(0, 19).toString();
String rDate = newDate.replace("T", " ");
String nDate = rDate.replaceAll("-", "/");
nDate will give you date in normal format, to compare two dates continue like
long epoch = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(nDate).getTime();
Date currentDate = new Date();
long diffInSeconds = (currentDate.getTime() - epoch) / 1000;
String elapsed = "";
long seconds = diffInSeconds;
long mins = diffInSeconds / 60;
long hours = diffInSeconds / 3600;
long days = diffInSeconds / 86400;
long weeks = diffInSeconds / 604800;
long months = diffInSeconds / 2592000;
if (seconds < 120) {
elapsed = "a min ago";
} else if (mins < 60) {
elapsed = mins + " mins ago";
} else if (hours < 24) {
elapsed = hours + " "+ (hours > 1 ? "hrs" : "hr")+ " ago";
} else if (hours < 48) {
elapsed = "a day ago";
} else if (days < 7) {
elapsed = days + " days ago";
} else if (weeks < 5) {
elapsed = weeks + " " + (weeks > 1 ? "weeks" : "week") + " ago";
} else if (months < 12) {
elapsed = months" " + (months > 1 ? "months" : "months")+ " ago";
} else {
elapsed = "more than a year ago";
}
This way you'll be able to get date in proper format as well as you'll be able to compare the dates and get the difference in Years, months, weeks, days, hours, mins or secs.