Im new to java and I want to convert months to years. For example, If i had 18 months and divided that by 12, I would have 1.5 years but I want it as 1year and 6months.
Thanks for your help.
Use the modulus %
.
int months = 18;
int years = months / 12; // 1
int remainingMonths = months % 12; // 6
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
. The Joda-Time team also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in [ThreeTenABP] (https://github.com/JakeWharton/ThreeTenABP).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Period
The Period
class tracks a span of time unrelated to the timeline in terms of years, months and days. Be sure to call normalized
as a habit to force it to recalculate eighteen months in terms of a year and six months.
Period period = Period.ofMonths( 18 ).normalized();
Extract the number of years and of months.
int years = period.getYears();
int months = period.getMonths();
You can call toString
to represent this value in standard ISO 8601 format for “durations”: PnYnMnDTnHnMnS
. In this format the P
marks the beginning while T
separates the years-months-days portion from hours-minutes-seconds portion (irrelevant in the case of this Question).
String output = period.toString();
P1Y6M
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With