Converting seconds to hours, minutes and seconds - java

I want to use count up timer in android for long hours...
Currently, I am using this code, but after some hours, say after 10 hours, the format goes like 10 : 650 :56 (hh:mm:ss)... for lesser time, it works perfectly...
private Runnable updateTimerMethod = new Runnable() {
public void run() {
timeInMillies = SystemClock.uptimeMillis() - startTime;
finalTime = timeSwap + timeInMillies;
int seconds = (int) (finalTime / 1000);
int minutes = seconds / 60;
int hours = minutes / 60;
seconds = seconds % 60;
int milliseconds = (int) (finalTime % 1000);
String timer = ("" + String.format("%02d", hours) + " : "
+ String.format("%02d", minutes) + " : "
+ String.format("%02d", seconds));
myHandler.postDelayed(this, 0);
sendLocalBroadcast(timer);
}
};

Your code for minutes is almost right, but you have to modulus it by 60 just like you do for seconds. Otherwise your value is going to still include all the hours.

Use this function:
private static String timeConversion(int totalSeconds) {
final int MINUTES_IN_AN_HOUR = 60;
final int SECONDS_IN_A_MINUTE = 60;
int seconds = totalSeconds % SECONDS_IN_A_MINUTE;
int totalMinutes = totalSeconds / SECONDS_IN_A_MINUTE;
int minutes = totalMinutes % MINUTES_IN_AN_HOUR;
int hours = totalMinutes / MINUTES_IN_AN_HOUR;
return hours + " : " + minutes + " : " + seconds;
}
You can found other solution in:
https://codereview.stackexchange.com/q/62713/69166

Related

Timer shows 010:00 after 10 minutes instead of 10:00

What do I have to change so that the timer is showing 10:00 after 10 minutes instead of 010:00. I know a bit how to solve it but it doesn't solve the original problem -- if delete the "0" from (textTimer.setText("0" + minutes + ":") it shows 0:00 when its under 10. How do I make it to show 10:00 after 10 minutes and 00:00 before 10 mins. Thanks
public void run() {
timeInMillies = SystemClock.uptimeMillis() - startTime;
finalTime = timeSwap + timeInMillies;
int seconds = (int) (finalTime / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
int milliseconds = (int) (finalTime % 1000);
textTimer.setText("0" + minutes + ":"
+ String.format("%02d", seconds));
myHandler.postDelayed(this, 0);
}
I'm not entirely sure why you're not formatting the entire string
textTimer.setText(String.format("%02d:%02d", minutes, seconds));

get duration in digital form

I have a music player which has a function called getcurrentposn which returns the current position in milliseconds, I want to display the result in the TextView in this form mm:ss.
I made a getAsTime function which have returns the time in my app in the digital form i.e. mm:ss.
This is what I tried:
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
long seconds = minutes * 60;
if(millis!=0) {
long totalSeconds = TimeUnit.MILLISECONDS.toSeconds(millis);
if(seconds!=0)
seconds = totalSeconds / seconds;
else seconds=totalSeconds;
}
if(minutes<10 && seconds <10)
return "0"+minutes + ":" +"0"+ seconds;
if(minutes<10 && seconds>=10)
return "0"+minutes + ":" + seconds;
if(minutes>=10 && seconds<10)
return minutes + ":" +"0"+ seconds;
return minutes+":"+seconds;
}
But the problem with that it is doesn't seem to work correctly.
Is there any inbuilt function to do so? if not how do I achieve it the correct way?
Example: 01:00
02:09
First convert the milliseconds to seconds:
int t = millis / 1000;
Then convert those to minutes and seconds
int minutes = t / 60; //since both are ints, you get an int
int seconds = t % 60;
Then return a string formatted like you want it with added padding
return String.format("%02d:%02d", minutes, seconds);

Convert long to remaining time

I'm currently trying to convert a long to a remaining time. I have got a
long remaining = XXXX
The long are the milliseconds to a certain date. For example: 3,600,000 should result in int weeks = 0, days = 0, hours = 1, minutes = 0, seconds = 0
how can I convert this long so that I end up with 5 ints:
int weeks;
int days;
int hours;
int minutes;
int seconds;
Thank you in advance!
DirtyDev
First, I suggest defining the number of ms in a second, minute, hour, etc as constants
static final int SECOND = 1000; // no. of ms in a second
static final int MINUTE = SECOND * 60; // no. of ms in a minute
static final int HOUR = MINUTE * 60; // no. of ms in an hour
static final int DAY = HOUR * 24; // no. of ms in a day
static final int WEEK = DAY * 7; // no. of ms in a week
Then, you can use basic division (/) and modulus (%) operations to find what you need.
long remaining = XXXX;
int weeks = (int)( remaining / WEEK);
int days = (int)((remaining % WEEK) / DAY);
int hours = (int)((remaining % DAY) / HOUR);
int minutes = (int)((remaining % HOUR) / MINUTE);
int seconds = (int)((remaining % MINUTE) / SECOND);
Excuse me, I don’t want to criticize too much, still I gather from the other answers that it’s easy to either write code that is hard to read or code with typos that gives an incorrect result. DirtyDev, I am aware that you may not be allowed to use Duration, but for anyone else:
long remaining = 3_600_000;
Duration remainingTime = Duration.ofMillis(remaining);
long days = remainingTime.toDays();
remainingTime = remainingTime.minusDays(days);
long weeks = days / 7;
days %= 7; // or if you prefer, days = days % 7;
long hours = remainingTime.toHours();
remainingTime = remainingTime.minusHours(hours);
long minutes = remainingTime.toMinutes();
remainingTime = remainingTime.minusMinutes(minutes);
long seconds = remainingTime.getSeconds();
System.out.println("" + weeks + " weeks " + days + " days "
+ hours + " hours " + minutes + " minutes " + seconds + " seconds");
This prints:
0 weeks 0 days 1 hours 0 minutes 0 seconds
It’s not perfect, but I believe it’s both readable, correct and robust. Duration was meant for times from hours down to nanoseconds, so we still have to do the weeks “by hand”.
Happy New Year.
This should do what you want.
long inputTimeInMilliseconds = 93800000;
long milliseconds = inputTimeInMilliseconds % 1000;
long seconds = (inputTimeInMilliseconds / 1000) % 60 ;
long minutes = ((inputTimeInMilliseconds / (1000*60)) % 60);
long hours = ((inputTimeInMilliseconds / (1000*60*60)) % 24);
long days = ((inputTimeInMilliseconds / (1000*60*60*24)) % 7);
long weeks = (inputTimeInMilliseconds / (1000*60*60*24*7));
String remainingTime = "time:"+weeks+":"+days+":"+ hours+":"+minutes+":"+seconds+":"+milliseconds;
System.out.println(remainingTime);

How to find the difference between times

I am trying to make a program for to find the difference between two hours.
The program searching in to the database of mongoDB all the hours and it must find every time the difference between them. But I do not know how to give the second value to take it every time in the loop.
Until now i make to find one time and to subtract from one standar.
How i can put to searching for the first two values of time in a loop...every time.
Thank you very much for your help!!!
int count = 1;
int start = 1;
while (cursorEvents.hasNext()) {
DBObject documentInEventCollection = cursorEvents.next();
if("pageLoad".equals(documentInEventCollection.get("type"))){
System.out.println("URL(" + count + "): " + documentInEventCollection.get("url").toString());
System.out.println("time-start(" + start + "): " + documentInEventCollection.get("timeStamp").toString());
count++;
start++;
try {
String timeStart = (documentInEventCollection.get("timeStamp").toString());
String timeStop = ("2015-07-24;12:26:54");
SimpleDateFormat format = new SimpleDateFormat("yyyy-dd-MM;HH:mm:ss");
Date d1 = null;
Date d2 = null;
d1 = format.parse(timeStart);
d2 = format.parse(timeStop);
//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();
}
}
}
I use follow solution to calculate a time different:
//Compute the time diff
Map<TimeUnit, Long> deltaTime = computeDiff(now.getTime(), target.getTime());
//Get the specific values
long d = deltaTime.get(TimeUnit.DAYS);
long m = deltaTime.get(TimeUnit.MINUTES);
long s = deltaTime.get(TimeUnit.SECONDS);
Methode code:
private static Map<TimeUnit, Long> computeDiff(Date start, Date end) {
long diffMilTime = end.getTime() - start.getTime();
List<TimeUnit> units = new ArrayList<>(EnumSet.allOf(TimeUnit.class));
Collections.reverse(units);
Map<TimeUnit, Long> result = new LinkedHashMap<>();
long restMilTime = diffMilTime;
for (TimeUnit unit : units) {
long diff = unit.convert(restMilTime, TimeUnit.MILLISECONDS);
long diffInMilliesForUnit = unit.toMillis(diff);
restMilTime = restMilTime - diffInMilliesForUnit;
result.put(unit, diff);
}
return result;
}

How to add n hours in java

I have n no of times.
ex:-
01:00:06
02:30:00
05:00:09
01:59:06
10:15:06
I want to add all this times. Finally calculate how may hours, min and seconds.
Please let me an idea to solve this.
I ma trying to do this using Calendar.
Updated:-
private void test() {
String[] dates = { "01:00:06", "02:30:00", "05:00:09", "01:59:06",
"10:15:06" };
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
Calendar calendar = Calendar.getInstance();
long totalHours;
for (int i = 0; i < dates.length; i++) {
calendar.setTime(ConstantFunction.StringToDate("HH:mm:ss",
dates[i]));
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
if (i == 0) {
calendar1.add(Calendar.HOUR_OF_DAY, hours);
calendar1.add(Calendar.MINUTE, minutes);
calendar1.add(Calendar.SECOND, seconds);
} else {
calendar2.add(Calendar.HOUR_OF_DAY, hours);
calendar2.add(Calendar.MINUTE, minutes);
calendar2.add(Calendar.SECOND, seconds);
}
}
long diffInMilis = calendar2.getTimeInMillis()
- calendar1.getTimeInMillis();
long diffInSecond = diffInMilis / 1000;
long diffInMinute = diffInMilis / (60 * 1000)% 60;
long diffInHour = diffInMilis / (60 * 60 * 1000);
System.out.println("diffInSecond==> " + diffInSecond);
System.out.println("diffInMinute==> " + diffInMinute);
System.out.println("diffInHour==> " + diffInHour);
}
I am do like this. But here I am getting wrong output.
diffInSecond==> 67455
diffInMinute==> 44
diffInHour==> 18
Finally I conclude with this solution. But I don't know this is a correct way to do this. Bu I got expected OP.
private void test() {
String[] dates = { "01:00:06", "02:30:00", "05:00:09", "01:59:06",
"10:15:06" };
long totalSecs=0;
for(int i=0;i<dates.length;i++){
totalSecs+=GetSeconds(dates[i]);
}
long hours = totalSecs / 3600;
long minutes = (totalSecs % 3600) / 60;
long seconds = totalSecs % 60;
System.out.println("hours==> " + hours);
System.out.println("minutes==> " + minutes);
System.out.println("seconds==> " + seconds);
}
private long GetSeconds(String time){
String[] parts = time.split(":");
long totSec=0;
int hour=Integer.parseInt(parts[0]);
int min=Integer.parseInt(parts[1]);
int sec=Integer.parseInt(parts[2]);
totSec=(hour*3600)+(min*60)+sec;
return totSec;
}

Categories