Converting multiple representations of time to minutes - java

my first post here, apologies if I have missed something fairly obvious in previous answers. I have several running times of films and albums represented in the following ways..
hh:mm:ss
hh:mm
5 hrs
5 hrs 55 mins
55 mins
555 mins.
I need a script that takes whichever one of these formats the compiler receives and turns it into a simple int representing the minutes.
Looking over previous questions on converting time to mins, I'm here so far..
for(runtime != null)
{
//Get rid of "mins", "hrs"..
runtime.replaceAll("[a-zA-Z]", "");
//Split time into parts dependent on the length of runtime..
String[] parts = runtime.split(":",runtime.length());
String hrs = parts[0];
String mins = parts[1];
String secs = parts[2];
if (hrs != null)
{
// hrs * 60
}
if (secs != null)
{
//secs / 60
}
//convert all to int
//hrs + mins + secs
}
I'm fairly new to this but if I'm not mistaken, the number being split may mean in some representations of the runtime, the minutes, hours and seconds may become confused.. Really not sure where to go with this. Help would be much appreciated

As you have said that your runtime can be in any of the format ,
So if you time is in 5hrs:32min then you will likely to have
Index out of bounds exception
So Assuming you will maintain the order of runtime in HH : MM : SS
String[] parts = runtime.split(":",runtime.length());
int length=parts.length;
String hrs=null,mins=null,secs=null
switch(length){
case 3:
hrs = parts[0];
mins = parts[1];
secs = parts[2];
break;
case 2:
// populate 1st 2
case 1:
// populate only 1st one
}
Now time to calculate , parsing you can do via Integer.parseInt(hrs) same for mins and secs .
int totalTimeInMinutes= (hr*60)+min+(sec%60f);

If you want to convert time in minutes, you should do it like,
int hr, sec;
if (hrs != null)
{
hr = hrs * 60
}
if (secs != null)
{
sec = (secs % 60) * 0.01;
}
//convert all to float
int time = hr + mins + sec;
This will convert 2hrs 20mins 20secs into 140.20 mins

Using Joda-Time, as I suggested in my comment, your code would be:
long numberOfMinutes = new Duration(new DateTime(date1), new DateTime(date2)).getStandardMinutes();

Related

24 hour clock to 12 hour clock conversion - curly brace pairing issue

I'm a beginner learning Java, and I'm trying to write a program to convert a user-inputted time to 12-hour time, or if it is supplied in 12-hour time format, to convert it to 24 hour time.
I have written some code, which worked as I tested it step by step, until I tried to modify to convert time from 12 hour to 24 hour format.
My code is below. I apologize for the redundancies and highly inefficient technique, but hey, I have to start somewhere. I believe my issue is in separating blocks of code, as I am trying to have a primary if statement to test whether the input ends with 'm' (i.e. if it's in 12 hour or 24 hour time when inputted), and then several nested if, else and else if statements.
import java.util.Scanner;
public class TimeConverter
{
public static void main ( String [] args )
{
Scanner ask_user = new Scanner (System.in);
System.out.println("Enter a time ([h]h:mm [am|pm]): ");
String enter_time = ask_user.nextLine ();
String am_pm = enter_time.substring(6);
String am = ("am");
String pm = ("pm");
if (enter_time.substring(7).equals("m"))
{
if (am_pm.equals(am))
{
String am_12 = enter_time.substring(0, 2);
String mins = enter_time.substring(2,5);
int am_12i = Integer.parseInt(am_12);
if (am_12i != 12)
{
String am_sub = enter_time.substring(0,5);
System.out.println(am_sub);
}
else if (am_12i == 12)
{
System.out.println("00" + mins);
}
}
else if (am_pm.equals(pm))
{
if (enter_time.equals("12:00 pm"))
{
System.out.println(enter_time);
}
else
{
String minutes = enter_time.substring(2,5);
String pm_add = enter_time.substring(0,2);
int pm_add_i = Integer.parseInt(pm_add);
int pm_add_fin = pm_add_i + 12;
String pm_add_finS = Integer.toString(pm_add_fin);
String converted_pmtime = (pm_add_finS + minutes);
System.out.println(converted_pmtime);
}
else if (enter_time.substring(7) != ("m"))
{
String 24hour = enter_time.substring(0,2);
String 12hourmins = enter_time.substring(2,7);
int 24hournum = Integer.parseint(24hour);
if (enter_time.equals("00:00"))
{
System.out.println("12" + 12hourmins);
}
else if (24hournum <= 11)
{
String hour = Integer.toString(24hournum);
String minute = enter_time.substring(2,4);
String fin = (hour + minute + "am");
}
}
}
}
The real problem is that you didn't indent your code properly. Once you do that, it will be a lot easier for you to detect the problems by yourself.
A few bugs I found from just quickly looking at your code:
You are missing a few parentheses. (Again, proper indentation will help with this a lot.)
if (enter_time.equals("12:00 pm"))
{
System.out.println(enter_time);
}
else
{
String minutes = enter_time.substring(2,5);
String pm_add = enter_time.substring(0,2);
int pm_add_i = Integer.parseInt(pm_add);
int pm_add_fin = pm_add_i + 12;
String pm_add_finS = Integer.toString(pm_add_fin);
String converted_pmtime = (pm_add_finS + minutes);
System.out.println(converted_pmtime);
}
else if (enter_time.substring(7) != ("m"))
{
You have a if statement. You then end the block with an else statement. There, however, is then and else if statement following the else. else if statements needs to be placed after the if statement and before the else statement. Either, the order of the else and else if statements are mixed up, or you are missing a closing bracket, }, after the else statement, and the else if part is really supposed to be part of the previous block.
You are also missing a closing bracket at the end of your code.
Variables cannot start with a number. All your variables like 24hournum and 24hour are invalid.
In the following line, int 24hournum = Integer.parseint(24hour);, you use parseint instead of parseInt.
My advice is to:
Properly indent all your code. Most IDEs come with shortcuts to easily do this.
Read and research all error and warning messages shown in your console.
Debug and step through your code to find what part exactly is causing the error.

Java getDuration(2.5d, TimeUnitType.Hour) no return duration in format ISO8601

I need duration in format ISO8601. https://en.wikipedia.org/wiki/ISO_8601#Durations.
Example :
double dur = 1442.7; //hrs
java.time.Duration d = java.time.Duration.ofMinutes((long)dur.convert(0).toDouble());
System.out.println(d.toString()); //// **1- issue of truncate real number ???**
2- I notice MsProject in the tag Value of Duration expects to always have a duration value of the ISO8601 form but at least with "H, M and S" (example: PT4H0M0S) whereas in this case Java.time.Duration return "PT4H" which is not valid for MsProject and this gives me the figure that we have nothing to what I expected. ????
There is no built-in way to do this but you can format it manually by adapting the code in this answer:
public static void main(String[] args) {
double dur = 1442.7; //hrs
java.time.Duration d = java.time.Duration.ofMinutes((long) dur);
System.out.println(format(d)); //PT24H2M0S
}
public static String format(java.time.Duration duration) {
long seconds = duration.getSeconds();
long absSeconds = Math.abs(seconds);
String positive = String.format(
"PT%dH%dM%dS",
absSeconds / 3600,
(absSeconds % 3600) / 60,
absSeconds % 60);
return seconds < 0 ? "-" + positive : positive;
}

convert a 4-digit military time into the standard 12 hour time format

What I'm trying to do:
I'm trying to convert a 4-digit military time into the standard 12 hour time format, with a colon and an added PM or AM without the use of importing anything before my code (I'm making a method that requires nothing other than java 101 techniques).
My situation:
I have milTime, which I manually change around for now every time I run it(as declared up top, currently at 1100), until I convert it into a method and submit the assignment, in which it will take in milTime, and will return milTimeString for the main program to print. I'm currently using BlueJ as an IDE, (I'm not sure if that's the best one to use?)
Example of input and output:
If 0056 were given, I would have to return 12:56am.
If 1125 were given, I would have to return 11:25am.
If 2359 were given, I would have to return 11:59pm.
Issues I need help with
When I execute, my am / pm boolean fails somewhere and it always outputs pm, no matter if I input 11:24 or 23:24.
It's probably obvious I'm working too hard to generate the output, but I don't know an easier way (Other than importing something to do it for me, which I don't want to do).
I humbly submit to any criticism on my bloated current code, and any corrections in my long-winded request. I've looked around for alternate answers, and everything involved importing or knowledge beyond me. Thanks for your time so far, and thanks in advance everyone.
public class timeTest
{
public static void main(String []args)
{
/*Declare my variables*/
int milTime = 2400;
String timeString = "";
boolean pm;
/*determine AM or PM and convert over 1200 into a clock's digits */
if (milTime >1259)
{
if (milTime <1200)
{
pm = false;
}
else
{
pm = true;
}
milTime = (milTime - 1200);
}
else
{
}
/*figure out my digits*/
int fourthDigit = milTime%10;
milTime = milTime/10;
int thirdDigit = milTime%10;
milTime = milTime/10;
int secondDigit = milTime%10;
milTime = milTime/10;
int firstDigit = milTime%10;
/*build each side of the colon*/
String hoursString = thirdDigit + "" + fourthDigit;
String minutesString = firstDigit + "" + secondDigit;
/*determine if the first digit is zero and if so, omit it*/
if (firstDigit == 0 )
{
minutesString = "" + secondDigit;
}
else
{
}
if (secondDigit == 0)
{
minutesString = "12";
}
else
{
}
/*build the total string and return the result with AM or PM based on conditional boolean.*/
if (pm = true)
{
timeString = (minutesString + ':' + hoursString + "pm");
}
else
{
}
if (pm = false)
{
timeString = (minutesString + ':' + hoursString + "am");
}
else
{
}
System.out.println(timeString);
}
}
Your problem is screaming out that you should be using your own custom data formatter. I like using the Joda Time library and its DateTime class instead of the built-in Java Date and Calendar classes. Therefore, instead of SimpleDateFormat, I recommend that you use a DateTimeFormat to create a DateTimeFormatter, which you will then use to convert your String into a DateTime. You will need one DateTimeFormatter for each of input and output. For example:
String rawTimestamp = "2300"; // For example
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("HHmm");
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("hh:mm a");
DateTime dateTime = inputFormatter.parseDateTime(rawTimestamp);
String formattedTimestamp = outputFormatter.print(dateTime.getMillis());
return formattedTimestamp;
Try this out!
You can do this much, much simpler, using a clever string conversion and SimpleDateFormat, here is the example but parsed in two lines:
// Heres your military time int like in your code sample
int milTime = 56;
// Convert the int to a string ensuring its 4 characters wide, parse as a date
Date date = new SimpleDateFormat("hhmm").parse(String.format("%04d", milTime));
// Set format: print the hours and minutes of the date, with AM or PM at the end
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
// Print the date!
System.out.println(sdf.format(date));
// Output: 12:56 AM
if (pm = true)
if (pm = false)
A single equal sign is an assignment. You want to do a comparison:
if (pm == true)
if (pm == false)
These could also be written more idiomatically as:
if (pm)
if (!pm)
That's the main problem. Another is your logic for setting pm. You only need a single if statement, with the line subtracting 1200 placed inside the pm = true block.
if (milTime < 1200)
{
pm = false;
}
else
{
pm = true;
milTime -= 1200;
}
There are a few other bugs that I'll leave to you. I trust these corrections will get you a bit further, at least.
public static String convert24HourToAmPm(String time) {
if (time == null)
return time;
// Convert time where time is like: 0100, 0200, 0300....2300...
if (time.length() == 4 && Helper.isInteger(time)) {
String hour = time.substring(0,2);
String minutes = time.substring(2,4);
String meridian = "am";
if (hour.substring(0,2).equals("00")) {
hour = "12";
} else if (hour.substring(0,1).equals("1") || hour.substring(0,1).equals("2")) {
meridian = "pm";
Integer militaryHour = Integer.parseInt(hour);
Integer convertedHour = null;
if (militaryHour > 12) {
convertedHour = (militaryHour - 12);
if (convertedHour < 10)
hour = "0" + String.valueOf(convertedHour);
else
hour = String.valueOf(convertedHour);
}
}
time = hour + ":" + minutes + " " + meridian;
}
// TODO - Convert time where time is like 01:00...23:00...
return time;
}

How to format Duration string?

I have a string with value as "3D7H40M20S"
Which should be converted as 3 Days 7 Hours 40 Minutes and 20 Seconds".
Here is what I tried so far:
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
AttributeBinding attr = (AttributeBinding)bindings.getControlBinding("ScreeningSLAWaitTimeDuration");
scrSlaWaitDur = (String)attr.getInputValue();
System.out.println("-------------------------------------------SCREENING SLA WAIT DURATION---------------"+scrSlaWaitDur);
scrSlaWaitDur = scrSlaWaitDur.substring(2, scrSlaWaitDur.length());
System.out.println("--------------------------------------------SUBSTRING--------------------"+scrSlaWaitDur);
int dIndex = scrSlaWaitDur.indexOf("D");
System.out.println("*******************************************INDEX OF D**********************************"+dIndex);
if(dIndex != -1){
String newDur = scrSlaWaitDur.substring(0, dIndex)+" days "+scrSlaWaitDur.substring(dIndex+1);
int mIndex = scrSlaWaitDur.lastIndexOf("M");
String newDur2 = scrSlaWaitDur.substring(0, mIndex)+" minute "+scrSlaWaitDur.substring(mIndex+1);
int sIndex = newDur2.lastIndexOf("S");
String newDur3 = newDur2.substring(0,sIndex)+" second";
scrSlaWaitDur = newDur3;
return scrSlaWaitDur;
}
I know this is quite tiresome and quite lengthy.
Can I achieve the requirement in a simpler way?
A pragmatic approach would be replacing the unit tokens:
return scrSlaWaitDur.replace("D", " Days ").replace("H", " Hours ").replace("M", " Minutes ").replace("S", " Seconds");
Output:
3 Days 7 Hours 40 Minutes 20 Seconds
You can use substring() without index(), i.e.:
String result =
scrSlaWaitDur.replace("D"," Days ").replace("H"," Hours ").replace("M"," Minutes ").replace("S"," Seconds");
But I'm sure someone will come up with a fency regex solution. ;-)

Value of chronometer into string

I'm trying to multiply the value of my chronometer or just try to get the value to be a string.
Every time I try to make it a string and use toast.show() to view it, my application crashes. I can get the value of my EditText to show up but I can't seem to get my chronometer to work. Both the strings time and fin make it crash. Here's the code:
String hour = String.valueOf(mText.getText());
String time = String.valueOf(mChronometer.getBase() - stoppedMilliseconds);
int h = java.lang.Integer.parseInt(hour) / 60;
int t = java.lang.Integer.parseInt(time) * 1000 / 60;
int mm = h * t;
mon.setText(Integer.toString(mm));
String fin = "" + mm;
Toast.makeText(PoopActivity.this,
"Money made: " + fin, Toast.LENGTH_LONG).show();
There are several defects obscuring the function of this code.
time is always negative. Swap the subtraction arguments.
When converting hour from hours to minutes, multiply rather than divide by 60.
When converting time from milliseconds to minutes, divide rather than multiply by 1000.
Computation of mm yields a quantity in minutes squared. This can hardly have any meaning.
Use getApplicationContext instead of PoopActivity. Some application other than PoopActivity may be running.
There is no exception handling. For all we know, mon may be null and the setText throw an exception. Wrap your code in a try - finally block:
String fin = "";
try
{
// most of your code goes here
mon.setText(Integer.toString(mm));
String fin += mm;
}
catch (Exception e)
{
// display the exception here if so inclined
}
finally
{
Toast.makeText(PoopActivity.this,
"Money made: " + fin, Toast.LENGTH_LONG).show();
}
However, fin is a string containing a negative number just fine.

Categories