How to parse time durations from Strings and add them? - java

I need to parse two Strings in HH:MM format in Java:
String time1="10:45";
String time2="02:30";

Stupid but simple:
String time1 = "10:45";
String time2 = "02:30";
String[] split1 = time1.split(":");
String[] split2 = time2.split(":");
int total = 60 * Integer.parseInt(split1[0]) +
Integer.parseInt(split1[1]) +
60 * Integer.parseInt(split2[0]) +
Integer.parseInt(split2[1]);
int hours = total / 60;
int minutes = total - hours * 60;
System.out.println(hours + ":" + minutes);

Do you want to get the difference? have a look at the SimpleDateFormat, perhaps you use that to create a Date and then calculate on that.

Use SimpleDateFormat to get teh dates
DateFormat formatter = new SimpleDateFormat("HH:mm");
Date date = (Date)formatter.parse("10:20");
Then you can add the dates together.
You may have to do some logic to cope with times where the dateas go over different days. I would recommend using JodaTime for any date manipulation.
Not sure if this is relevant as not sure what the actual question is....

Related

Calculate time difference in java

I want to calculate time difference in java. I am calculating successfully only in between 1 hour. When I enter the time above 1 hour calculation is getting Wrong.
String start= "12:00:00";
String end= "12:50:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(start);
Date date2 = format.parse(end);
long difference = date2.getTime() - date1.getTime();
System.out.println(difference/1000);
double time = difference/1000;
double tot = time/60;
JOptionPane.showMessageDialog(this, tot);
result displayed 50mins successfully from above code
I modified the same code and it looks like this:
String start = "12:00:00";
String end = "01:50:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(start);
Date date2 = format.parse(end);
long difference = date2.getTime() - date1.getTime();
System.out.println(difference/1000);
double time = difference/1000;
double tot = time/60;
JOptionPane.showMessageDialog(this, tot);
here result displayed
-610.0 I don't know why I need to display the output of 1.50
Because you input the time in the AM|PM form, but your code is supposed to work with the 24-hour time format.
Change the time from
String end = "01:50:00";
to
String end = "13:50:00";
and it will work like a charm :)
(Or you can change the code to work with AM-PM time model, but it will be more difficult.
Actually, I would use the new OffsetTime classes to solve this problem.
Here is some example code:
public static void distance(String strTime1, String strTime2) {
OffsetTime time1 = OffsetTime.parse(strTime1);
OffsetTime time2 = OffsetTime.parse(strTime2);
int time1Seconds = time1.get(ChronoField.MINUTE_OF_DAY);
int time2Seconds = time2.get(ChronoField.MINUTE_OF_DAY);
System.out.println("Time 1 in seconds: " + time1Seconds);
System.out.println("Time 1 in seconds: " + time2Seconds);
System.out.println("Distance: " + Math.abs(time1Seconds - time2Seconds));
}
What you are doing is to parse a String simliar to yours. As a difference, I would recommend you to always add timezone information. Since it probably doesn't matter much in your case, I'd just add +00:00.
Please not Maths.abs(). As long as you are interested in the distance between both times and not in which direction the distance is, you can use this to get rid of minus or plus prefixes and use the absolute value.
That way you can create OffsetTime by parsing this string. After that you can read the minute of the day.
Please try it with:
public static void main(String[] args) {
distance("10:00:00+00:00", "12:00:00+00:00");
distance("12:30:00+00:00", "12:31:00+00:00");
distance("12:31:00+00:00", "12:30:00+00:00");
}
The results would be:
Time 1 in seconds: 600
Time 1 in seconds: 720
Distance: 120
Time 1 in seconds: 750
Time 1 in seconds: 751
Distance: 1
Time 1 in seconds: 751
Time 1 in seconds: 750
Distance: 1
You mentioned that you need fractions of minutes, like 1.5. Fractions are always complicated and not precise. That's why people invented BigDecimal. However, in your case BigDecimal doesn't help. I would recommend you to use a smaller unit, like seconds.
Just change your code to:
int time1Seconds = time1.get(ChronoField.SECOND_OF_DAY);
int time2Seconds = time2.get(ChronoField.SECOND_OF_DAY);
Here is some Javadocs:
https://docs.oracle.com/javase/8/docs/api/index.html?java/time/LocalDateTime.html
And a tutorial to the new classes (JDK8):
https://docs.oracle.com/javase/tutorial/datetime/iso/timezones.html
From SimpleDateFormat
Letter | Date or Time Component
H | Hour in day (0-23) .
h | Hour in am/pm (1-12)
So in your case you have "HH:mm:ss" which stands for 24Hr time format.
and its start from 00:00 till 23:59
So you can change this to like below for above pattern:
String start = "12:00:00";
String end = "13:50:00";
Or you can change your pattern like below:
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
String start = "12:00:00";
String end = "01:50:00";
See result: code output

Convert String "01-09-2015' to Long - Java/Android

Hi I have a String like this "01-09-2015"
I need to convert this string to long.
I have tried using
String date = "01-09-2015";
Long dateLong = Long.getLong(date);
Long dateLong = Long.valueOf(date);
Long dateLong = Long.valueOf(date,36);
Long dateLong = Long.parseLong(date);
Still no help. Everything returns be NumberFormatException.
Anyone please help.
Thanks in advance.
EDIT
Guys, I will send in a String, which is of course a date like "08-01-2015". For each unique string which I pass, I need a unique long value. Thats all.
You have to convert it to Date first before changing it to Long
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yy");
Date d = format.parse("01-09-2015");
long milliseconds = d.getTime();
I recommend you split the input on -, then convert the three date parts to int; and then concatenate them into a long. Something like,
String date = "01-09-2015";
String[] arr = date.split("-");
int yyyy = Integer.valueOf(arr[2]);
int mm = Integer.valueOf(arr[0]);
int dd = Integer.valueOf(arr[1]);
long dateLong = (yyyy * 10000) + (mm * 100) + dd;
System.out.println(dateLong);
Output is (the unique, per date)
20150109
Note This is in keeping with ISO 8601; the linked Wikipedia article says (in part)
ISO 8601 Data elements and interchange formats – Information interchange – Representation of dates and times is an international standard covering the exchange of date and time-related data.

How can i format a decimal value into hours and minutes?

for example if the user input is 1.71 (1 hour and 71 minutes), then i want to convert it to 2.11 (2 hours and 11 minutes)
DecimalFormat time = new DecimalFormat("##.## p.m");
int userInput = 1.71;
System.out.print(time.format(userInput));
Parse the input as date and than format the date to your output format:
Scanner sc = new Scanner(System.in);
DateFormat df = new SimpleDateFormat("HH.mm");
DateFormat dfout = new SimpleDateFormat("H.mm a");
Date date = df.parse(sc.next());
System.out.println(dfout.format(date));
I'm not sure whether I get your question right, but shouldn't the following work?
int hours = (int)userInput;
decimal minutestmp = ((userInput - hours) * 60);
int minutes = (int)minutestmp;
String TimeString = hours + ":" + minutes;
Date date = new SimpleDateFormat("HH:mm").parse(TimeString);
String newTimeString = new SimpleDateFormat("H:mm").format(date);
ISO 8601
The ISO 8601 standard for date-time strings defines a format for what they call Durations: PnYnMnDTnHnMnS.
Joda-Time
The Joda-Time library knows how to parse and generate such strings.
So first, transform your input into such a string. Then feed that new string into Joda-Time. Lastly ask Joda-Time to recalculate the hours and minutes. All of this has been covered on StackOverflow multiple times. Please search for details.
To translate that input, replace the period, and prepend and append.
String d = "PT" + "1.71".replace( ".", "H") + "M"; // PT1H71M
Feed to Joda-Time.
Period period = Period.parse( d );
Normalize the minutes.
Period p = period.normalizedStandard();
Alternatively, you could tear apart the hours and minutes portions of your input, then feed them as ints to a constructor of Period.

Format decimal that represents hour into HH:mm

I'm trying formatting a Double that represents hour like this:
Double totalHours = 1.05;
int hour = totalHours.intValue();
Long minutes = Math.round((totalHours - hour) * 60);
System.out.println(hour + ":" + minutes);
In this case I get "1:3" but I wold like "01:03". How would I do this?
Or there's a better way to do this?
Use a DecimalFormat:
DecimalFormat df = new DecimalFormat("00"); // "0" means don't omit leading zero
System.out.println(df.format(hour) + ":" + df.format(minutes));
Use String.format("%02d:%02d", hour, minutes)
Try this:
String strHourFormat = "HH";
SimpleDateFormat sdf = new SimpleDateFormat(strHourFormat);
sdf = new SimpleDateFormat(strHourFormat);

how to parse this date

I cant quite figure out what the format should be to parse this date. Its a millisecond value followed by timezone. thx.
// so far tried: "S Z"
// "SSSSSSSSSSS-ZZZZ",
// "SSSSSSSSSSS-Z",
// etc.
Format formatter = new SimpleDateFormat("SSSSSSSSSSSS Z", Locale.CANADA);
// source string looks like this /Date(928164000000-0400)/
String temp = jsonUserObj.getString("DateOfBirth").substring(6, 6+17);
System.err.println("got date="+temp);
Date date = (Date) formatter.parseObject(temp);
You can do it without parser.
String[] parts = new String[]{temp.substring(0, temp.indexOf('-')), temp.substring(temp.indexOf('-') + 1)};
long millis = Long.parseLong(parts[0]);
parts[1] = parts[1].replaceAll("^0*(\\-?[0-9]*)$", "$1");
int timeZone = Integer.parseInt(parts[1]);
int rawOffset = (timeZone / 100) * 3600000 + (timeZone % 100);
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(millis);
cal.setTimeZone(new SimpleTimeZone(rawOffset, "GMT"));
SimpleDateFormat expects a milliseconds value < 1000, as it expects you would increment seconds, then minutes, etc, for larger values.
You'll need to convert the value first; this post might help: Unix epoch time to Java Date object

Categories