简体   繁体   English

如何在 java 中将月份转换为年份和月份

[英]How to convert months to years-and-months in java

Im new to java and I want to convert months to years.我是 java 的新手,我想将几个月转换为几年。 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.例如,如果我有 18 个月并将其除以 12,我将有 1.5 年,但我希望它为 1 年和 6 个月。

Thanks for your help.谢谢你的帮助。

Use the modulus % .使用模数%

int months = 18;
int years = months / 12; // 1
int remainingMonths = months % 12; // 6

java.time java.time

The java.time framework is built into Java 8 and later.java.time框架内置于 Java 8 及更高版本中。 These classes supplant the old troublesome date-time classes such as java.util.Date , .Calendar , & java.text.SimpleDateFormat .这些类取代了旧的麻烦的日期时间类,例如java.util.Date.Calendarjava.text.SimpleDateFormat The Joda-Time team also advises migration to java.time. Joda-Time团队还建议迁移到 java.time。

To learn more, see the Oracle Tutorial .要了解更多信息,请参阅Oracle 教程 And search Stack Overflow for many examples and explanations.并在 Stack Overflow 上搜索许多示例和解释。

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 ). 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. ThreeTen-Extra项目通过附加类扩展了 java.time。 This project is a proving ground for possible future additions to java.time.该项目是未来可能添加到 java.time 的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more.您可能会在这里找到一些有用的类,例如IntervalYearWeekYearQuarter等等。

Period

The Period class tracks a span of time unrelated to the timeline in terms of years, months and days. Period class 跟踪与时间线无关的时间跨度,以年、月和日表示。 Be sure to call normalized as a habit to force it to recalculate eighteen months in terms of a year and six months.请务必将normalized称为一种习惯,以迫使它以一年零六个月的时间重新计算十八个月。

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 .您可以调用toString以标准ISO 8601格式表示此值,用于“持续时间”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).在这种格式中, P标记开始,而T将年-月-日部分与小时-分钟-秒部分分开(与本问题无关)。

String output = period.toString(); 

P1Y6M P1Y6M

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM