Format decimal that represents hour into HH:mm - java

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);

Related

Java Subtract 2 duration in HH:MM:SS

I have 2 string in java (HH:MM:SS) please take note this is not time, but duration, i used end time - start time to get these values:
Case1:
duration1 = "12:04:45";
duration2 = "13:04:45";
Expected result: duration1 - duration 2 = "-1:00:00" (Note that there is negative)
Case2:
duration1 = "15:13:32";
duration2 = "12:04:45";
Expected result: duration1 - duration 2 = "3:08:47"
How can i do that? My attempt for the Case1 (codes modified from Java add dates of format dd:HH:mm:ss):
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String s1 = "12:04:45";
String s2 = "13:04:45";
Date d1 = format.parse(s1);
Date d2 = format.parse(s2);
int sec = d1.getSeconds() - d2.getSeconds();
int min = d1.getMinutes() - d2.getMinutes();
int hr = d1.getHours() - d2.getHours();
Time sum = new Time(hr, min, sec);
System.out.println(sum); // Output: 23:00:00 which is wrong
Using LocalTime or date calculations like some people suggest doesn't work if your period involved more than 24 hours since that doesn't fit in a day.
If you don't have Java 8, you can use JodaTime. I've just checked that this code also works with JodaTime 1.6.2, which is the last version that still works with JDK 1.4.2.
PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroAlways().minimumPrintedDigits(2)
.appendHours().appendSuffix(":").appendMinutes().appendSuffix(":").appendSeconds()
.toFormatter();
Period period1 = formatter.parsePeriod("12:04:45");
Period period2 = formatter.parsePeriod("13:04:45");
Period difference1 = period1.minus(period2).normalizedStandard();
System.out.println(formatter.print(difference1));
Period period3 = formatter.parsePeriod("15:13:32");
Period period4 = formatter.parsePeriod("12:04:45");
Period difference2 = period3.minus(period4).normalizedStandard();
System.out.println(formatter.print(difference2));
Output:
-01:00:00
03:08:47
JodaTime:
Version 1.6.2 source: https://github.com/JodaOrg/joda-time/releases/tag/v1.6.2
Version 1.6.2 Maven Jar artifact: http://mvnrepository.com/artifact/joda-time/joda-time/1.6.2
With the Java time API you could use a Duration to calculate the duration and format it as you want:
String s1 = "12:04:45";
String s2 = "13:04:45";
LocalTime t1 = LocalTime.parse(s1);
LocalTime t2 = LocalTime.parse(s2);
Duration d = Duration.between(t2, t1);
System.out.println(d); //PT-1H
If you want to print it as -1:00:00 you will need to tweak the output format. It could look like this:
private static String toHHMMSS(Duration d) {
long hours = d.toHours();
int minutes = (int) (d.toMinutes() % 60);
int secs = (int) (d.getSeconds() % 60);
return hours + ":" + minutes + ":" + secs;
}
Use Calendar to calculate the time difference.
You can query each field and/or format as a time string as this example shows:
private Calendar getTimeDiffDate(Date d1, Date d2) {
Calendar c = Calendar.getInstance();
c.setTime(new Date(d1.getTime()-d2.getTime()));
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
// Format as a time string:
String formattedTime = formatter.format(c.getTime());
System.out.println("formattedTime: "+formattedTime);
// Query by each field:
System.out.println("Hours: "+c.get(Calendar.HOUR));
System.out.println("Minutes: "+c.get(Calendar.MINUTE));
System.out.println("Seconds: "+c.get(Calendar.SECOND));
return c;
}

mean time of two string time in java

I have two times variable as string
want to find the mean time. please help me
inTime = shift.getInTime()+":00";
outTime = shift.getOutTime()+":00";
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
Date d1=df.parse(inTime);
Date d2 = df.parse(outTime);
long date1InMilSec=d1.getTime();
long date2InMilSec=d2.getTime();
long half =date1InMilSec + ((date2InMilSec - date1InMilSec) / 2);
long minute = (half / (1000 * 60)) % 60;
long hour = (half / (1000 * 60 * 60)) % 24;
String time = String.format("%02d:%02d", hour, minute);
First of all, if I use your code and set fixed time values, then I get 11:30:00 instead of your 07:00:00, so there is maybe something else wrong with inTime and outTime.
Since I get 11:30:00 there is maybe something wrong with your calculation of hour and minute, but I won't bother that. Let's use a new Date instance to do the conversion:
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
Date d1 = df.parse("09:30:00");
Date d2 = df.parse("15:30:00");
long date1InMilSec = d1.getTime();
long date2InMilSec = d2.getTime();
long half = date1InMilSec + ((date2InMilSec - date1InMilSec) / 2);
Date meanTime = new Date(half); // new Date instance, instead of own calculation
String time = df.format(meanTime);
System.out.println(time);
This code prints:
12:30:00
String inTime = "09:30:00";
String outTime = "15:30:00";
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
Date dateIn = df.parse(inTime);
Date dateOut = df.parse(outTime);
long dateInMill = dateIn.getTime();
long dateOutMill = dateOut.getTime();
long dateMiddleMill = dateInMill + ((dateOutMill - dateInMill) / 2);
Date dateMiddle = new Date(dateMiddleMill);
System.out.println(df.format(dateMiddle));

How to parse time durations from Strings and add them?

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....

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

How to convert minutes to HH:mm on android?

I have String variable movieDuration, which contains value in minutes. Need to convert that to HH:mm format. How should I do it?
Tried to do it as:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
movieDurationFormatted = formatter.format(movieDuration);
But looks like value in minutes is not ok for formatter.
public static String formatHoursAndMinutes(int totalMinutes) {
String minutes = Integer.toString(totalMinutes % 60);
minutes = minutes.length() == 1 ? "0" + minutes : minutes;
return (totalMinutes / 60) + ":" + minutes;
}
Just use the following method to convert minutes to HH:mm on android?
if you want to process long value then just change the parameter type
public static String ConvertMinutesTimeToHHMMString(int minutesTime) {
TimeZone timeZone = TimeZone.getTimeZone("UTC");
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
df.setTimeZone(timeZone);
String time = df.format(new Date(minutesTime * 60 * 1000L));
return time;
}
Happy coding :)
Solution on kotlin Documentation
import kotlin.time.Duration
import kotlin.time.DurationUnit
import kotlin.time.toDuration
val min = 150.toDuration(DurationUnit.MINUTES)
val time = min.toComponents { days, hours, minutes, seconds, nanoseconds ->
"$days $hours $minutes $seconds $nanoseconds"
}
We get 0 days 2 hours 30 minutes 0 seconds 0 nanoseconds
We can also use
DurationUnit.DAYS
DurationUnit.HOURS
DurationUnit.SECONDS
DurationUnit.MILLISECONDS
DurationUnit.MICROSECONDS
DurationUnit.NANOSECONDS

Categories