Show the format XX:00 in JAVA - java

I want to show a number in a format XX:00 in Java. How can I do it?
Ex: int number = 12;
show 12:00.
double i = 12;
show 12:00

Showing a double number
If 12.0 is a fractional number to be printed with colon as decimal separator:
double i = 12;
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator(':');
NumberFormat format = new DecimalFormat("00.00", dfs);
System.out.println(format.format(i));
Output:
12:00
If i was 12.75 instead of 12, the fraction would be printed too:
12:75
It rounds to the nearest number with two decimals, so 12.756 would be printed as 12:76.
Showing a duration in hours and minutes
If instead your 12:00 denotes an amount of time, a duration in hours and minutes, we want something different because there are 60 minutes in an hour, not 100. Here’s the Java 9 and later version:
long totalMinutes = (long) (i * TimeUnit.HOURS.toMinutes(1));
Duration dur = Duration.ofMinutes(totalMinutes);
System.out.format("%02d:%02d%n", dur.toHours(), dur.toMinutesPart());
This prints
12:00
or in the 12.75 case:
12:45
12.75 equals 12 and three quarters, and the 45 printed also equals three quarters of an hour, so this is what we wanted. It rounds down, so even though 12.759 equals 12 hours 45 minutes 32.4 seconds, it’s still printed as 12:45.
Java 8 and earlier:
The toMinutesPart method I have used was introduced in Java 9. In Java 8 (and earlier) you may still use the Duration class, but it’s less advantageous, so you may also do without it:
int hours = (int) i;
long minutesOnly = totalMinutes - TimeUnit.HOURS.toMinutes(hours);
System.out.format("%02d:%02d%n", hours, minutesOnly);
Now the result is the same as above.

double i = 12;
String.format("%.0f:00", i); // returns 12.00

Related

Dividing seconds by 60 twice to get hours results in zero

I'm trying to convert the number of seconds contained in a duration into hours by dividing the duration.getSeconds() value by 60 twice.
However when I do this the number is being converted into 0.0, instead of an actual value. I imagine this is because the number is too small to be represented, however I have used doubles to try and represent the number and it still doesn't work.
In the below code please assume startTime and endTime are valid LocalTimes produced by two separate calls to LocalTime.now()
Duration duration = Duration.between(startTime, endTime); //duration in sec
double durationInSec = duration.getSeconds();
double durationInHours = durationInSec / 60 / 60;
Works for me
LocalTime start = LocalTime.of ( 11 , 30 );
LocalTime stop = start.plusHours ( 2 );
Duration d = Duration.between ( start , stop );
double seconds = d.toSeconds ();
double hours = seconds / 60 / 60;
See this code run live at IdeOne.com.
start.toString() = 11:30
stop.toString() = 13:30
d.toString() = PT2H
seconds = 7200.0
hours = 2.0
Tip: When you know you want to work with fractions of double, append d to your numeric literals to avoid any confusion over the compiler's integer-to-fraction conversion and up/downscaling the types. Be explicit. So in your code, append each 60 with a d. May not be necessary here, but removes ambiguity for the reader at least.
double hours = seconds / 60d / 60d ;
<1 second = 0 hours
As others commented, if your elapsed time was less than a full second, your code results in a zero.
A Duration is internally represented by a count of whole seconds plus a fractional second as a count of nanoseconds. Your call to Duration::getSeconds() retrieves the whole seconds, without the fractional second. So for a duration of PT0.5S, getSeconds returns zero. Zero divided by sixty divided by sixty equals zero.
Duration d = Duration.parse ( "PT0.5S" ); // Half a second.
double hours = d.getSeconds () / 60d / 60d;
hours: 0.0
You should instead call Duration::toNanos to get a total number of nanoseconds elapsed. And adjust your division.
Duration d = Duration.parse ( "PT0.5S" ); // Half a second.
long nanos = d.toNanos () ;
double hours = nanos / 1_000_000_000d / 60d / 60d ;
hours: 1.388888888888889E-4
Avoid fractional hours
By the way, let me suggest that fractional hours is a poor way to handle spans-of-time. Hours, minutes, seconds, and such are not amenable to such decimal math.
Besides that, the floating-point types such as double are inherently inaccurate.
Use the Java classes intended for this purpose: Duration and Period. When reporting or exchanging textually the value of these objects, use standard ISO 8601 format. As seen above, 2 hours is represented by PT2H.
The java.time classes use ISO 8601 formats by default when parsing/generating strings. No need to specify a formatting pattern.
Duration d = Duration.parse( "PT2H" ) ;

Convert Minutes to Hours using JodaTime

I'm having Minutes in java.lang.Long and want to convert this value to java.math.BigDecimal, ie. as Hours.
BigDecimal hours = BigDecimal.valueOf(minutes)
.divide(BigDecimal.valueOf(DateTimeConstants.MINUTES_PER_HOUR))
.setScale(2,RoundingMode.HALF_DOWN);
Tried the above method. It return hours, but no the way actually i want it
How i need is :
240 Minutes : 4 Hours
230 Minutes : 3.50 hours
Any help?
I would convert your Minutes to a Period object:
Minutes minutes = ...;
Long millisec = minutes*60*1000;
Period period = new Period(millisec);
Then use the Period object you can ask the Hours. Anything you want...
Note: 230 minutes is not 3.50 hours, it's 3.83 hours, i'm assuming you mean "3 hours and 50 minutes".
So what you want is the hh:mm representation.
You don't need BigDecimals. Use this:
long minutes = 230;
long hours = minutes / 60;
long minnutesRemaining = minutes % 60;
System.out.println(hours + "." + minnutesRemaining);
I'm betting the OP actually wants to convert minutes into hours and minutes. This is as easy as:
int minutes = 230;
System.out.println(
String.format("%d Minutes: %d:%02d Hours", minutes, (minutes/60), (minutes%60)));
Just printing the minutes divided by 60 (using integer arithmetic) and the modulo of minutes divided by 60 (formatted as two digits with leading zeros by the "%02d" format.
You can do this using BigDecimal easy. You can use divideAndRemainder()
long minutes = 230L;
BigDecimal min = new BigDecimal(minutes);
BigDecimal constant = new BigDecimal(60);
BigDecimal[] val=min.divideAndRemainder(constant);
System.out.println(val[0]+"."+val[1]+" Hours");
Out put:
3.50 Hours
I don't know in what universe 230 minutes equals 3.5 hours, so I'm afraid that some string manipulation is your best bet:
BigDecimal hours = new BigDecimal(
String.format("%d.%d", minutes / 60, minutes % 60));
Printing out the value of hours yields 3.50, as per your requirement.
Use integer and modulo arithmetic:
long hours = minutes / 60; /*implicit round-down*/
long numberAfterDecimal = (minutes % 1.0 /*pull out the remainder*/) * 60;
Then format these two numbers as you wish.

Time Difference separating the times

Complete timeDifference that takes two different times and returns a
string with the difference in hours and minutes, separated by ":".
The int argument 0 represents midnight, 700 is 7:00 a.m., 1314 is 14
minutes past 1:00pm, and 2200 is 10 pm.
Leading zeros required
I know the problem requires you to convert both times to minutes, however I don't know how to separate the integers that are four characters long so I can differ between hours and minutes.
Sice your question is on the separation part only, this will do the trick:
int timeDifference(int a, int b)
{
int minsA = a % 100); //remainder
int hrsA = (a / 100);
.....
}
Edit: if you want to get the full time just in minutes you can do:
int fullMinsA = minsA + hrsA*60;

Loss of precision - Java

Problem Statement:
Write a method whatTime, which takes an int, seconds, representing the number of seconds since midnight on some day, and returns a String formatted as "::". Here, represents the number of complete hours since midnight, represents the number of complete minutes since the last complete hour ended, and represents the number of seconds since the last complete minute ended. Each of , , and should be an integer, with no extra leading 0's. Thus, if seconds is 0, you should return "0:0:0", while if seconds is 3661, you should return "1:1:1"
My Algorithm:
Here is how my algorithm is supposed to work for the input 3661:
3661/3600 = 1.016944 -> This means the number of hours is 1
Subtract the total number of hours elapsed i.e. 1.016944-1=0.016944
Multiply this with 60 i.e. 0.016944*60=1.016666 -> The number of minutes elapsed is equal to 1
Subtract the total number of minutes elapsed i.e. 1.01666-1=0.01666. Multiply this with 60. This would yield the number of seconds elapsed.
The output produced however is 1:1:0. I tried to use a print statement and it appears that the value of 'answer3' variable is 0.999 and that is why prints the integer part (0). I tried to use the Math.ceil() function to round up the value and it produces a correct output. However I can only score about 60/250 points when I submit my code (TopCoder SRM 144 Div2) . Any insight for improving the algorithm will be helpful.
public class Time
{
public String whatTime(int seconds)
{
double answer1,answer2,answer3; int H;
answer1=(double)seconds/3600;
H=(int)answer1;
answer2=(double)((answer1-H)*60);
int M=(int)answer2;
answer3=answer2-M;
answer3=(double)answer3*60;
int S=(int)answer3;
String answer=Integer.toString(H);
answer=Integer.toString(H)+":"+Integer.toString(M)+":"+Integer.toString(S);
return answer;
}
}
public String whatTime(int seconds) {
int secondVal = seconds % 60;
int minutes = seconds / 60;
int minuteVal = minutes % 60;
int hours = minutes / 60;
int hourVal = hours % 24;
int daysVal = hours / 24;
String answer = "" + daysVal + ":" + hourVal + ":" + minuteVal + ":" + secondVal;
return answer;
}
Could do the formatting more elegantly, but that's the basic idea.
Avoid floating point values, and work entirely with ints or longs.
You could solve this by working with ints :
3661/3600 = 1.016944 -> This means the number of hours is 1
Subtract the number of hours * 3600 - i.e. 3661-(1*3600) = 61
61/60 = 1.0166666 -> The number of minutes elapsed is equal to 1
Subtract the number of minutes * 60 i.e. 61-(1*60)=1. This yields the number of seconds elapsed.

Period between dates using Java/Joda

I have 2 joda dates as follows:
org.joda.time.DateTime a;
org.joda.time.DateTime b;
I want the difference between the 2 dates in terms of Years, months and days (eg. 0 years, 2 months, 5 days).
I can use the org.joda.time.Days.daysBetween(a, b) or monthsBetween(a, b) or yearsBetween(a, b) to get the whole values of each respectively.
Since a month does have number of fixed number of days, how can I calculate this?
Eg. If I get monthsbetween = 2 and daysbetween = 65, how can I write this as "2 months and x days"
Is there any other way to get this?
Try this:
Calendar ca = Calendar.getInstance();
ca.setTime(a);
Calendar cb = Calendar.getInstance();
cb.setTime(b);
System.out.printf("%d months and %d days"
, ca.get(Calendar.MONTH) - cb.get(Calendar.MONTH)
, ca.get(Calendar.DAY_OF_MONTH) - cb.get(Calendar.DAY_OF_MONTH));
Im not too familiar with Joda, but it looks like your best option is to divide the days left by 30.5, and then round it up back to a whole integer. Like so:
double daysDivided = daysbetween / 30.5;
int daysbetweenFixed = (int) daysDivided;
System.out.printf("%d months and %d days", monthsbetween, daysbetweenFixed);
//optional output ^
I'm sure you would know i chose 30.5 because it seems like the a good average month length, excluding February. Because there is no set length of a month this is the best we can do with only these integers.

Categories

Resources