简体   繁体   English

如何获取年-月格式的时间段?

[英]How can I get time period in years-months format?

I have two strings like "March 2012" and "April 2013" . 我有两个字符串,例如"March 2012""April 2013" I need to subtract these dates and get something like: "1 year 2 month" . 我需要减去这些日期,并得到类似"1 year 2 month"

I know how to get it in days: 我知道如何在几天内得到它:

df.parse(secondDate).getTime() - df.parse(firstDate).getTime())/(1000*60*60*24)

but I will receive 395 days. 但我会收到395天。 How can I get it in years-month format? 如何获得年月格式? I know it should be easy but I cannot guess how to do that. 我知道这应该很容易,但是我无法猜测如何做到这一点。

For this type of problem, it is best to use the new Java Time API that was introduced in Java 8. 对于此类问题,最好使用Java 8中引入的新Java Time API

We have 2 Strings that represent a year and a month. 我们有2个代表一年零一个月的字符串。 Therefore, we will parse each String into a YearMonth object using a custom DateTimeFormatter . 因此,我们将使用自定义DateTimeFormatter将每个String解析为YearMonth对象。 The month names are in their long English form so we will use the pattern "MMMM yyyy" . 月份名称采用英文长格式,因此我们将使用模式"MMMM yyyy"

Once they are parsed, we can get the period between those two temporal objects with Period.between . 解析它们之后,我们可以使用Period.between获得这两个时间对象之间的时间Period.between This method takes a LocalDate as parameter so we need to add a day to each YearMonth : here, we will set it to the first day of the month (what matters is that both are set to the same day). 此方法采用LocalDate作为参数,因此我们需要为每个YearMonth添加一天:在这里,我们将其设置为该月的第一天(重要的是两者都设置为同一天)。

Finally, getYears() return the amount of years in this period and getMonths() returns the amount of month. 最后, getYears()返回此时间段中的年数,而getMonths()返回月的量。

public static void main(String[] args) {
    String startStr = "March 2012";
    String endStr = "April 2013";

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy", Locale.ENGLISH);
    YearMonth start = YearMonth.parse(startStr, formatter);
    YearMonth end = YearMonth.parse(endStr, formatter);

    Period period = Period.between(start.atDay(1), end.atDay(1));

    System.out.println(period.getYears() + " years and " + period.getMonths() + " months.");
    // prints "1 years and 1 months." (you could add check for the pluralization of course ;) )
}

With this method, you don't need to worry about tricky considerations, it is handled automatically by the API. 使用此方法,您无需担心棘手的注意事项,它会由API自动处理。

Make use of the Java8 API java.time.Period , which gives you a date-based amount of time: 利用Java8 API java.time.Period ,它为您提供基于日期的时间量:

Period p = Period.between(firstDate, secondDate);
System.out.println(p.getYears()+" years, " + p.getMonths() + " months, and " + p.getDays() + " days.");

Check the below example, it should work correctly and solve leap year case as depend on year and month only: 检查以下示例,它应能正常工作并解决仅取决于年份和月份的leap年情况:

     public static void main(String[] a) throws Exception {

    //some data initilzation for the sample
    Date d1 = new Date(), d2 = new Date();
    d1.setYear(d1.getYear() - 1); //Just for the sample, replace it with your dates
    d1.setMonth(d1.getMonth() + 5);//Just for the sample, replace it with your dates

    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(d1);
    int year1 = calendar1.get(Calendar.YEAR);
    int month1 = calendar1.get(Calendar.MONTH) + 1;

    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(d2);
    int year2 = calendar2.get(Calendar.YEAR);
    int month2 = calendar2.get(Calendar.MONTH) + 1;

    int yearDiff = year2 - year1;
    int monthDiff = month2 - month1;

    //Logic, in case d1  Jul 2015 and d2 Feb 2016, the need to reduce one year and put the remaining months on monthDiff value
    if (monthDiff < 0) {
        yearDiff = yearDiff - 1;
        monthDiff = monthDiff + 12;
    }

    System.out.println(" " + d1);
    System.out.println(" " + d2);

    System.out.println("yearDiff " + yearDiff + "     " + "monthsDiff " + monthDiff);

}

You can customize the below code as your need: 您可以根据需要自定义以下代码:

import java.util.*;
import java.lang.*;
import java.io.*;

import java.util.Calendar;
import java.text.SimpleDateFormat;

class MyClass
{
    public static void main(String[] args) throws Exception
    {
        MyClass tdt = new MyClass();
        System.out.println("Date: "+tdt.doSubtractMath("31/10/2000","31/12/2016").getTime());
    }
    /**
    * method to create a calendar object, subtract time, and return result
    */
    private Calendar doSubtractMath(String firstDate, String secondDate) throws Exception
    {
        SimpleDateFormat sdf = new SimpleDateFormat("d/MM/yyyy");

        Calendar secondDateCalender = Calendar.getInstance();

        secondDateCalender.setTime(sdf.parse(secondDate));


        Calendar firstDateCalendar = Calendar.getInstance();

        firstDateCalendar.setTime(sdf.parse(firstDate));

        secondDateCalender.add(Calendar.MINUTE, -1 * firstDateCalendar.get(Calendar.MINUTE));

        secondDateCalender.add(Calendar.HOUR, -1 * firstDateCalendar.get(Calendar.HOUR));

        secondDateCalender.add(Calendar.DAY_OF_MONTH, -1 * firstDateCalendar.get(Calendar.DAY_OF_MONTH));

        secondDateCalender.add(Calendar.YEAR, -1 * firstDateCalendar.get(Calendar.YEAR));

        return secondDateCalender;

    }
}

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

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