How to sum total number of hours ,minutes,seconds in java? - java

Am having a doubt on how to sum total number of hours minutes seconds in java for example i have 160:00:00 and 24:00:00 and 13:50:00 and 00:10:00 i need to get grand sum like 198:00:00 how can i calculate this so far what i have tried is
for(int i=0;i<addnoteobj.size();i++){
String s = addnoteobj.get(i).getDuration();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String[] tokens = s.split(":");
int hours = Integer.parseInt(tokens[0]);
int minutes = Integer.parseInt(tokens[1]);
int seconds = Integer.parseInt(tokens[2]);
duration = 3600 * hours + 60 * minutes + seconds;
int j = duration/3600;
int h= (duration%3600) / 60;
int m = (duration % 60);
hourss=hourss+j;
mm=mm+h;
sss=sss+m;
date3 = hourss + ":" + mm + ":" + ss;
String time = simpleDateFormat.format(new Date(duration*1000L));
Log.d("dat",time);
try {
date=simpleDateFormat.parse(s);
ss=ss+date.getTime();
date3 = simpleDateFormat.format(new Date(ss));
// total=dates.getTime();
Log.d("time",date3);
} catch (ParseException e) {
e.printStackTrace();
}
}
But i cannot achieve this how to do this am having total hours in list how to get total hours thanks in advance

java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern Date-Time API:
You can use java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenient methods were introduced.
Assuming all the string are in the form of HH:mm:ss format, you can split them on : and then combine the parts to form a string in the ISO 8601 pattern for a duration which can be parsed using Duration#parse.
Demo:
import java.time.Duration;
public class Main {
public static void main(String[] args) {
String[] strDurationArr = {
"160:00:00",
"24:00:00",
"13:50:00",
"00:10:00"
};
Duration sum = Duration.ZERO;
for (String strDuration : strDurationArr) {
sum = sum.plus(parseStrDuration(strDuration));
}
System.out.println(formatDurationJava8Plus(sum));
System.out.println(formatDurationJava9Plus(sum));
}
static Duration parseStrDuration(String strDuration) {
String[] arr = strDuration.split(":");
String strIsoDuration = "PT" + arr[0] + "H" + arr[1] + "M" + arr[2] + "S";
return Duration.parse(strIsoDuration);
}
static String formatDurationJava8Plus(Duration duration) {
return String.format("%d:%02d:%02d", duration.toHours(), duration.toMinutes() % 60, duration.toSeconds() % 60);
}
static String formatDurationJava9Plus(Duration duration) {
return String.format("%d:%02d:%02d", duration.toHours(), duration.toMinutesPart(), duration.toSecondsPart());
}
}
Output:
198:00:00
198:00:00
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

I have intentionally left the println so that you can see the code flow. hope this helps you...
public static void main(String[] args) {
String time[] = { "160:00:00", "24:00:00", "13:50:00", "00:10:00" };
int hours = 0, minutes = 0, seconds = 0;
for (String string : time) {
String temp[] = string.split(":");
hours = hours + Integer.valueOf(temp[0]);
minutes = minutes + Integer.valueOf(temp[1]);
seconds = seconds + Integer.valueOf(temp[2]);
}
System.out.println(hours + ":" + minutes + ":" + seconds);
if (seconds == 60) {
minutes = minutes + 1;
seconds = 0;
} else if (seconds > 59) {
minutes = minutes + (seconds / 60);
seconds = seconds % 60;
}
System.out.println(hours + ":" + minutes + ":" + seconds);
if (minutes == 60) {
hours = hours + 1;
minutes = 0;
} else if (minutes > 59) {
hours = hours + (minutes / 60);
minutes = minutes % 60;
}
System.out.println(hours + ":" + minutes + ":" + seconds);
String output = "";
output = String.valueOf(hours);
output = output.concat(":" + (String.valueOf(minutes).length() == 1 ? "0" + String.valueOf(minutes) : String.valueOf(minutes)));
output = output.concat(":" + (String.valueOf(seconds).length() == 1 ? "0" + String.valueOf(seconds) : String.valueOf(seconds)));
System.out.println(output);
}

I didn't test it but I'm pretty sure it's something like this:
private static String sumTime(String t1, String t2){
byte extraMinutes=0;
byte extraHours=0;
String arrt1[] = t1.split(":");
String arrt2[] = t2.split(":");
int seconds = Integer.valueOf(arrt1[2]) + Integer.valueOf(arrt2[2]);
if(seconds>=60) {
extraMinutes = 1;
seconds = seconds % 60;
}
int minutes = Integer.valueOf(arrt1[1]) + Integer.valueOf(arrt2[1]) + extraMinutes;
if(minutes>=60){
extraHours = 1;
minutes = minutes % 60;
}
int hours = Integer.valueOf(arrt1[0]) + Integer.valueOf(arrt2[0]) + extraHours;
if(hours>=24) hours = hours%24;
return hours+":"+minutes+":"+seconds;
}

Related

convert time(12h and 24h)

I'm writing a program that converts the time (12h and 24h).
The result I want to get is the following:
convertTime ("12:00") ➞ "0:00"
convertTime ("6:20 pm") ➞ "18:20"
convertTime ("21:00") ➞ "9:00 pm"
convertTime ("5:05") ➞ "5:05"
this is my code, unfortunately the result is not what I expected, in fact:
A time input of 12 hours will be indicated with an am or pm suffix.
An input time of 24 hours contains no suffix.
I would appreciate a help so much, thanks in advance!
public static String convertTime(String time) {
String hour = time.substring(0, time.indexOf(":"));
String min = time.substring(3, time.indexOf(":") + 3);
int hourInteger = Integer.parseInt(hour);
if (hourInteger > 12 && hourInteger < 24) {
hourInteger = hourInteger - 12;
}
if (hourInteger == 24) {
hourInteger = 0;
}
if (hourInteger < 12) {
return hourInteger + ":" + min + " AM";
}
if (hourInteger > 12)
return hourInteger + ":" + min + " PM";
return hourInteger;
}
You can use below code snippet, you can make additional changes accordingly as your wish. Using Date API to parse vise versa 12 <-> 24 Hours format.
public static String convertTime(String time) throws ParseException {
if (time.contains("am") || time.contains("pm")) {
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
Date date = parseFormat.parse(time);
return displayFormat.format(date);
} else {
SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat displayFormat = new SimpleDateFormat("hh:mm a");
Date date = parseFormat.parse(time);
return displayFormat.format(date);
}
}
There were few problems with your code.
One is return hourInteger. As the convertTime() return type is String, you can't return an Integer. To convert it you can use,
String.valueOf(hourInteger);
Second in 24h clock format, there is no 24:00. A minute after 23:59 is 00:00. So,
if (hourInteger == 24) {
should be,
if (hourInteger == 0) {
Third,
if (hourInteger > 12 && hourInteger < 24) {
hourInteger = hourInteger - 12;
}
above code will convert all possible hours larger than 12 to hours smaller than 12. So after that line checking if(hourInteger>12) always returns false.
Below code will work for your situation.
public static String convertTime(String time) {
String hour = time.substring(0, time.indexOf(":"));
String min = time.substring(3, time.indexOf(":") + 3);
int hourInteger = Integer.parseInt(hour);
int newHour = hourInteger;
if (hourInteger > 12 && hourInteger < 24) {
newHour = hourInteger - 12;
}
if (hourInteger==0) {
newHour = 12;
}
if (hourInteger < 12) {
return newHour + ":" + min + " AM";
}else {
return newHour + ":" + min + " PM";
}
}
You can use StringTokenizer to split the string into tokens using delimiters : and , then convert based on number of tokens (2 for 24 hour format, 3 for 12 hour format):
import java.util.*;
public class Main
{
public static String convertTime(String time) {
StringTokenizer sb = new StringTokenizer(time, ": ");
if (sb.countTokens() == 2)
{
// 24 hr to 12 hr
int hour = Integer.parseInt(sb.nextToken());
int min = Integer.parseInt(sb.nextToken());
boolean isEvening = false;
if (hour >= 12 && hour <= 24)
{
hour -= 12;
if (hour != 0)
isEvening = true;
}
return String.format("%02d:%02d %s", hour, min, (isEvening ? "pm" : "am"));
}
else if (sb.countTokens() == 3)
{
// 12 hr to 24 hr
int hour = Integer.parseInt(sb.nextToken());
int min = Integer.parseInt(sb.nextToken());
boolean isEvening = sb.nextToken().equalsIgnoreCase("pm");
if (isEvening || hour == 0)
{
hour += 12;
}
return String.format("%02d:%02d", hour, min);
}
return "";
}
public static void main(String[] args) {
System.out.println(convertTime("12:00"));
System.out.println(convertTime("6:20 pm"));
System.out.println(convertTime("21:00"));
System.out.println(convertTime("5:05"));
}
}

add string time with overflow hour in java

I want to add string time with format HH:mm:ss and special hour field. Example :
"20:15:30" (string) add "13:50:35" (string) -> result i want : "34:06:05" (string).
I have search similar code :
String time1="20:15:30";
String time2="13:50:35";
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date1 = timeFormat.parse(time1);
Date date2 = timeFormat.parse(time2);
long sum = date1.getTime() + date2.getTime();
String date3 = timeFormat.format(new Date(sum));
System.out.println("The sum is "+ date3);
And result of above code : The sum is 10:06:05 not i want. How is easy way to do this ?
You could simply take advantage of either Java 8's or Joda Time's duration capabilities.
For example, this simply creates a duration which is the sum of the number of seconds of the two times
LocalTime lt1 = LocalTime.parse("20:15:30", DateTimeFormatter.ofPattern("HH:mm:ss"));
LocalTime lt2 = LocalTime.parse("13:50:35", DateTimeFormatter.ofPattern("HH:mm:ss"));
//long t = lt1.toSecondOfDay() + lt2.toSecondOfDay();
//Duration duration = Duration.ofSeconds(t);
Duration duration = Duration.between(lt2, lt1);
System.out.println(formatDuration(duration));
Which prints out 34:06:05
formatDuration method
public static String formatDuration(Duration duration) {
long hours = duration.toHours();
duration = duration.minusHours(hours);
long minutes = duration.toMinutes();
duration = duration.minusMinutes(minutes);
long seconds = duration.getSeconds();
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
SimpleDateFormat can't do that, but you can do it yourself, by parsing the input with a regular expression, and formatting the output with the format method.
private static String addTime(String ... times) {
if (times.length < 2)
throw new IllegalArgumentException("At least 2 times are required");
Pattern timePattern = Pattern.compile("([0-9]+):([0-5][0-9]):([0-5][0-9])");
// Parse times and sum hours, minutes, and seconds
int hour = 0, minute = 0, second = 0;
for (String time : times) {
Matcher m = timePattern.matcher(time);
if (! m.matches())
throw new IllegalArgumentException("Invalid time: " + time);
hour += Integer.parseInt(m.group(1));
minute += Integer.parseInt(m.group(2));
second += Integer.parseInt(m.group(3));
}
// Handle overflow
minute += second / 60; second %= 60;
hour += minute / 60; minute %= 60;
// Format and return result
return String.format("%02d:%02d:%02d", hour, minute, second);
}
Test
System.out.println(addTime("20:15:30", "13:50:35"));
System.out.println(addTime("20:15:30", "13:50:35", "20:15:30", "13:50:35"));
System.out.println(addTime("98765:43:21", "12:34:56"));
Output
34:06:05
68:12:10
98778:18:17

Need time difference with string like "A Min ago" or "An Hour Ago" [duplicate]

This question already has answers here:
How to calculate "time ago" in Java?
(33 answers)
Closed 8 years ago.
I am new in Android Development.
I need one help to convert my current time with one static time.
Your help be appreciated.
I have one string like this
String created_at = "Wed Mar 03 19:37:35 +0000 2010";
I want to convert it like , which means difference between my current time and created_at string.
23 mins ago // Example
Thanks,
Dharmik
Just use the following utility class I've created and pass the two date objects in its constructor .Subsequently use the getDifferenceString() method to obtain the same.
public class TimeDifference {
int years;
int months;
int days;
int hours;
int minutes;
int seconds;
String differenceString;
public TimeDifference(Date curdate, Date olddate) {
float diff=curdate.getTime() - olddate.getTime();
if (diff >= 0) {
int yearDiff = Math.round( ( diff/ (365l*2592000000f))>=1?( diff/ (365l*2592000000f)):0);
if (yearDiff > 0) {
years = yearDiff;
setDifferenceString(years + (years == 1 ? " year" : " years") + " ago");
} else {
int monthDiff = Math.round((diff / 2592000000f)>=1?(diff / 2592000000f):0);
if (monthDiff > 0) {
if (monthDiff > 11)
monthDiff = 11;
months = monthDiff;
setDifferenceString(months + (months == 1 ? " month" : " months") + " ago");
} else {
int dayDiff = Math.round((diff / (86400000f))>=1?(diff / (86400000f)):0);
if (dayDiff > 0) {
days = dayDiff;
if(days==30)
days=29;
setDifferenceString(days + (days == 1 ? " day" : " days") + " ago");
} else {
int hourDiff = Math.round((diff / (3600000f))>=1?(diff / (3600000f)):0);
if (hourDiff > 0) {
hours = hourDiff;
setDifferenceString( hours + (hours == 1 ? " hour" : " hours") + " ago");
} else {
int minuteDiff = Math.round((diff / (60000f))>=1?(diff / (60000f)):0);
if (minuteDiff > 0) {
minutes = minuteDiff;
setDifferenceString(minutes + (minutes == 1 ? " minute" : " minutes") + " ago");
} else {
int secondDiff =Math.round((diff / (1000f))>=1?(diff / (1000f)):0);
if (secondDiff > 0)
seconds = secondDiff;
else
seconds = 1;
setDifferenceString(seconds + (seconds == 1 ? " second" : " seconds") + " ago");
}
}
}
}
}
}
}
public String getDifferenceString() {
return differenceString;
}
public void setDifferenceString(String differenceString) {
this.differenceString = differenceString;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
public int getMonths() {
return months;
}
public void setMonths(int months) {
this.months = months;
}
public int getDays() {
return days;
}
public void setDays(int days) {
this.days = days;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
}
its is simple do something like this ( Note I don't have java etc installed I have just typed it in Note on my ipad, so I am not sure if it works but it should be something like this) :
String dateString = "Wed Mar 03 19:37:35 2010";
SimpleDateFormat dateFormat = new SimpleDateFormat("E M d hh:mm:ss y");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// convert date to calnedar
Calendar previouseCal = Calendar.getInstance();
previouseCal.setTime(convertedDate );
// then get the current time
Calendar currentCal = Calendar.getInstance();
// then get the diffrence
long difference = currentCal.getTimeInMillis() - previouseCal.getTimeInMillis();
// if you need it in second then
int second = TimeUnit.MILLISECONDS.toSeconds(difference)
I hope that helps :)

Converting date into text format

How do I convert date into its text format..for ex:if updated today..then instead of date it must show "Today",one day after it must show "Yesterday",and then after two days..it must display the date in general form(//_) on which it was updated..i tried using SimpleDateFormat..but not working..
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d= new Date();
//Convert Date object to string
String strDate = sdf.format(d);
System.out.println("Formated String is " + strDate);
d = sdf.parse("31-12-2009");
Plz help..
Thanks in advance..
Try this:
public class TimeUtils {
public final static long ONE_SECOND = 1000;
public final static long SECONDS = 60;
public final static long ONE_MINUTE = ONE_SECOND * 60;
public final static long MINUTES = 60;
public final static long ONE_HOUR = ONE_MINUTE * 60;
public final static long HOURS = 24;
public final static long ONE_DAY = ONE_HOUR * 24;
private TimeUtils() {
}
/**
* converts time (in milliseconds) to human-readable format
* "<w> days, <x> hours, <y> minutes and (z) seconds"
*/
public static String millisToLongDHMS(long duration) {
StringBuffer res = new StringBuffer();
long temp = 0;
if (duration >= ONE_SECOND) {
temp = duration / ONE_DAY;
if (temp > 0) {
duration -= temp * ONE_DAY;
res.append(temp).append(" day").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_HOUR;
if (temp > 0) {
duration -= temp * ONE_HOUR;
res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_MINUTE;
if (temp > 0) {
duration -= temp * ONE_MINUTE;
res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
}
if (!res.toString().equals("") && duration >= ONE_SECOND) {
res.append(" and ");
}
temp = duration / ONE_SECOND;
if (temp > 0) {
res.append(temp).append(" second").append(temp > 1 ? "s" : "");
}
return res.toString();
} else {
return "0 second";
}
}
public static void main(String args[]) {
System.out.println(millisToLongDHMS(123));
System.out.println(millisToLongDHMS((5 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR));
System.out.println(millisToLongDHMS(ONE_DAY + 2 * ONE_SECOND));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE)));
System.out.println(millisToLongDHMS((4 * ONE_DAY) + (3 * ONE_HOUR)
+ (2 * ONE_MINUTE) + ONE_SECOND));
System.out.println(millisToLongDHMS((5 * ONE_DAY) + (4 * ONE_HOUR)
+ ONE_MINUTE + (23 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(42 * ONE_DAY));
/*
output :
0 second
5 seconds
1 day, 1 hour
1 day and 2 seconds
1 day, 1 hour, 2 minutes
4 days, 3 hours, 2 minutes and 1 second
5 days, 4 hours, 1 minute and 23 seconds
42 days
*/
}
}
Take a look at the PrettyTime library.
You can check this Comparision of dates
import java.text.SimpleDateFormat;
import java.util.Date;
public class App {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
public static long ms, s, m, h, d, w;
static {
ms = 1;
s = ms * 1000;
m = s * 60;
h = m * 60;
d = h * 24;
w = d * 7;
}
public App() {
Date now = new Date();
Date old = new Date();
try {
old = sdf.parse("12-11-2013");
} catch (Exception e) {
e.printStackTrace();
}
long diff = now.getTime() - old.getTime();
if (diff < this.d) {
System.out.println("Today");
}
else if (diff > this.d && diff < this.d*2) {
System.out.println("Yesterday");
}
System.out.println("Difference: " + msToHms(diff));
}
public String msToHms(long ms) {
int seconds = (int) (ms / this.s) % 60 ;
int minutes = (int) ((ms / this.m) % 60);
int hours = (int) ((ms / this.h) % 24);
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
public static void main(String[] args) {
new App();
}
}
Output
Yesterday
Difference: 07:11:22
You have to implement your own logic based on the time difference and use the corresponding date format.
Lets assume you are getting a date from a server.
Get the device's time and compare to your date.
For your requirements there will be two cases.
The difference between the two date is less then a day, then return "Today" string.
The difference between the two date is grater then a day then use the Simple Date format to format your date as you want.
For comparing dates please see this entry: datecompare

I don't understand getNextIncludedTime() in Quartz

I'm probably just being an idiot - it's been a long day! I've misunderstood something in my first foray into Quartz...
Given this code:
DateTime dt = new DateTime();
dt = dt.withDayOfMonth(20);
Calendar cal = new CronCalendar("0 0/10 * * * ?" );
long start = dt.getMillis();
System.out.println("Starting at " + start);
long end = start + 10;
long current = start;
int i = 0;
while (current < end) {
if (i > 0) {
System.out.println(i + ":" + current);
}
long next = cal.getNextIncludedTime(current);
current = next;
i++;
}
I expect that there will be at most one included time in the output, as the time window is 10ms and the times included in the Calendar are 10 minutes apart.
But when I run it:
Starting at 1250796103004
1:1250796103005
2:1250796103006
3:1250796103007
4:1250796103008
5:1250796103009
6:1250796103010
7:1250796103011
8:1250796103012
9:1250796103013
Please help!
Yep, just me being a dumbass.
Calendars specify EXCLUDED times.
I should have been using a CronTrigger to specify the times I wanted to include. The code should look more like this...
CronTrigger cal = new CronTrigger("Test", "Test", "0 0/10 * * * ?" );
...
end = start + 1000000;
...
while (current < end) {
if (i > 0) {
System.out.println(i + ":" + current);
}
Date next = cal.getFireTimeAfter(new Date(current));
current = next.getTime();
i++;
}
Which gives the output I was expecting.
Starting at 1250798091337
1:1250798400000
2:1250799000000

Categories