I am saving Current Date time as Timestamp with below code in my Android
userValues.put("rTime", ServerValue.TIMESTAMP);
Now I want to calculate difference as
String posttime=1576917051506 //retrieve saved timestamp
String currenttime=ServerValue.TIMESTAMP //current time
difference=1hour 25 minutes
how can i achieve this
String posttime=1576917051506
String currenttime=ServerValue.TIMESTAMP
first of all convert times to Long
long time1 = Long.valueof(posttime)
long time2 = Long.valueof(currenttime)
long diffrence = time2-time1
String myValue = convertSecondsToHMmSs(diffrence)
Now myValue is your time diffrence. like 1h:2m
public static String convertSecondsToHMmSs(long millis) {
long seconds = (millis / 1000) % 60;
long minutes = (millis / (1000 * 60)) % 60;
long hours = millis / (1000 * 60 * 60);
StringBuilder b = new StringBuilder();
b.append(hours == 0 ? "00" : hours < 10 ? String.valueOf("0" + hours) :
String.valueOf(hours));
b.append(":");
b.append(minutes == 0 ? "00" : minutes < 10 ? String.valueOf("0" + minutes) :
String.valueOf(minutes));
b.append(":");
b.append(seconds == 0 ? "00" : seconds < 10 ? String.valueOf("0" + seconds) :
String.valueOf(seconds));
return b.toString();
}
Using Joda time:
DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
long hours = p.getHours();
long minutes = p.getMinutes();
Related
I've to 2 different epoch timestamp A and B. For each day i have different sunrise and sunset times.
Suppose for day 1, which is timestamp A day sunrise time is 6.00 am and sun set time as 6.30 pm and for day2, sunrise time is 6.05 am and sunset time is 6.25pm, etc., below is the format i have,
val sunRise = mapOf<Int,String>(1 to "6.00", 2 to "6.05",3 to "6.01", 4 to "6.06")
val sunSet = mapOf<Int,String>(1 to "18.30", 2 to "18.25",3 to "18.20", 4 to "18.23")
val startTime = 1579919400000
val endTime = 1580203800000
Now how to calculate time taken between these to timestamps which are only between sunRise and sunSet in Android
Try Below method will calculate difference between two times.
System.out.println("==result==: " + stringForTime(endTime - startTime));
public String stringForTime(long timeMs) {
long totalSeconds = timeMs / 1000;
long seconds = totalSeconds % 60;
long minutes = (totalSeconds / 60) % 60;
long hours = totalSeconds / 3600;
Formatter mFormatter = new Formatter();
if (hours > 0) {
return mFormatter.format("%02d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
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 ));
I need to get Day Hours Minutes to reach certain date
example :
Date = "14-08-2015 16:38:28"
Current_Date = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date());
and to reach that Date the result will be
2 Days and 1 hour and 30 minutes
Simple searching on google I got
String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 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();
}
see below links
http://www.mkyong.com/java/how-to-calculate-date-time-difference-in-java/
How to find the duration of difference between two dates in java?
Calculate date/time difference in java
You could use:
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
There are plenty of constants in Calendar for everything you need. Edit: Calendar class documentation
I want return millisecond to time
But my code not work !
long ms = 86400000;
long s = ms % 60;
long m = (ms / 60) % 60;
long h = (ms / (60 * 60)) % 24;
String timeFind = String.format("%d:%02d:%02d", h, m, s);
You could use SimpleDateFormat, but be aware that you should set both the time zone and the locale appropriately:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String text = formatter.format(new Date(millis));
The time zone part is important, as otherwise it will use the system-default time zone, which would usually be inappropriate. Note that the Date here will be on January 1st 1970, UTC - assuming your millisecond value is less than 24 hours.
You can use
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
1 second= 1000 milli seconds... Try now
or if you are trying to retrive the current time you could use Calendar class
Calendar cal = Calendar.getInstance();
String time =""+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE);
Use TimeUnit instead of do all that math, that way you make sure that this will actually work, and It's more readable.
Use my code simple and work for me
just call this function and put millisecond
public String settIMER(int time) {
String str = "00:00";
try {
long parseLong = time;
if (parseLong >= 3600000) {
try {
str = String.format(Locale.getDefault(), "%02d:%02d:%02d",
new Object[]{Long.valueOf(TimeUnit.MILLISECONDS.toHours(parseLong)),
Long.valueOf(TimeUnit.MILLISECONDS.toMinutes(parseLong) % TimeUnit.HOURS.toMinutes(1)),
Long.valueOf(TimeUnit.MILLISECONDS.toSeconds(parseLong) % TimeUnit.MINUTES.toSeconds(1))});
} catch (NumberFormatException unused) {
java.lang.System.out.println(parseLong);
}
} else {
str = String.format(Locale.getDefault(), "%02d:%02d",
new Object[]{Long.valueOf(TimeUnit.MILLISECONDS.toMinutes(parseLong) % TimeUnit.HOURS.toMinutes(1)),
Long.valueOf(TimeUnit.MILLISECONDS.toSeconds(parseLong) % TimeUnit.MINUTES.toSeconds(1))});
}
return str;
} catch (Exception e) {
return "00:00";
}
}
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);
}