Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert months to years-and-months in java

Tags:

java

date

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.

like image 899
asdf Avatar asked Jun 05 '11 22:06

asdf


2 Answers

Use the modulus %.

int months = 18;
int years = months / 12; // 1
int remainingMonths = months % 12; // 6
like image 60
BalusC Avatar answered Oct 24 '22 20:10

BalusC


java.time

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

like image 30
Basil Bourque Avatar answered Oct 24 '22 22:10

Basil Bourque