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

Java 如何获取年-月格式的时间段?,java,date,Java,Date,我有两个字符串,如“2012年3月”和“2013年4月”。我需要减去这些日期,得到如下结果:“1年2个月” 我知道如何在几天内得到它: df.parse(secondDate).getTime() - df.parse(firstDate).getTime())/(1000*60*60*24) 但我将收到395天的通知。我怎样才能得到年-月格式?我知道这应该很容易,但我猜不出怎么做。对于这类问题,最好使用Java 8中引入的新版本 我们有两个字符串,表示一年和一个月。因此,我们将使用自定义语法

我有两个字符串,如
“2012年3月”
“2013年4月”
。我需要减去这些日期,得到如下结果:
“1年2个月”

我知道如何在几天内得到它:

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

但我将收到395天的通知。我怎样才能得到年-月格式?我知道这应该很容易,但我猜不出怎么做。

对于这类问题,最好使用Java 8中引入的新版本

我们有两个字符串,表示一年和一个月。因此,我们将使用自定义语法将每个字符串解析为一个对象。月份名称采用长英文形式,因此我们将使用模式
“MMMM-yyyy”

一旦对它们进行了解析,我们就可以得到这两个时态对象之间的周期。此方法将
LocalDate
作为参数,因此我们需要为每个
YearMonth
添加一天:在这里,我们将其设置为每月的第一天(重要的是两者设置为同一天)

最后,返回此期间的年数,并返回月份数

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 ;) )
}

使用这种方法,您不必担心棘手的问题,它是由API自动处理的。

对于这种类型的问题,最好使用Java 8中引入的新方法

我们有两个字符串,表示一年和一个月。因此,我们将使用自定义语法将每个字符串解析为一个对象。月份名称采用长英文形式,因此我们将使用模式
“MMMM-yyyy”

一旦对它们进行了解析,我们就可以得到这两个时态对象之间的周期。此方法将
LocalDate
作为参数,因此我们需要为每个
YearMonth
添加一天:在这里,我们将其设置为每月的第一天(重要的是两者设置为同一天)

最后,返回此期间的年数,并返回月份数

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 ;) )
}

使用此方法,您无需担心棘手的问题,它由API自动处理。

利用Java8 API
java.time.Period
,它为您提供基于日期的时间量:

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

利用Java8API
java.time.Period
,它为您提供基于日期的时间量:

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

检查下面的示例,它应该正确工作,并解决闰年情况,因为它仅依赖于年份和月份:

     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);

}
publicstaticvoidmain(字符串[]a)引发异常{
//示例的一些数据初始化
日期d1=新日期(),d2=新日期();
d1.setYear(d1.getYear()-1);//对于示例,将其替换为日期
d1.setMonth(d1.getMonth()+5);//对于示例,将其替换为日期
Calendar calendar1=Calendar.getInstance();
日历1.设定时间(d1);
int year1=calendar1.get(Calendar.YEAR);
int month1=calendar1.get(Calendar.MONTH)+1;
Calendar calendar2=Calendar.getInstance();
日历2.设定时间(d2);
int year2=calendar2.get(Calendar.YEAR);
int month2=calendar2.get(Calendar.MONTH)+1;
int yearDiff=year2-year1;
int-monthDiff=month2-month1;
//逻辑上,在2015年7月1日和2016年2月2日的情况下,需要减少一年,并将剩余月份计入monthDiff值
if(monthDiff<0){
yearDiff=yearDiff-1;
monthDiff=monthDiff+12;
}
系统输出打印项次(“+d1”);
系统输出打印项次(“+d2”);
System.out.println(“yearDiff”+yearDiff++++“monthsDiff”+monthDiff);
}

检查下面的示例,它应该正确工作,并解决闰年情况,因为它仅依赖于年份和月份:

     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);

}
publicstaticvoidmain(字符串[]a)引发异常{
//示例的一些数据初始化
日期d1=新日期(),d2=新日期();
d1.setYear(d1.getYear()-1);//对于示例,将其替换为日期
d1.setMonth(d1.getMonth()+5);//对于示例,将其替换为日期
Calendar calendar1=Calendar.getInstance();
日历1.设定时间(d1);
int year1=calendar1.get(Calendar.YEAR);
int month1=calendar1.get(Calendar.MONTH)+1;
Calendar calendar2=Calendar.getInstance();
日历2.设定时间(d2);
int year2=calendar2.get(Calendar.YEAR);
int month2=calendar2.get(Calendar.MONTH)+1;
int yearDiff=year2-year1;
int-monthDiff=month2-month1;
//逻辑上,在2015年7月1日和2016年2月2日的情况下,需要减少一年,并将剩余月份计入monthDiff值
if(monthDiff<0){
yearDiff=yearDiff-1;
monthDiff=monthDiff+12;
}
系统输出打印项次(“+d1”);
系统输出打印项次(“+d2”);
System.out.println(“yearDiff”+yearDiff++++“monthsDiff”+monthDiff);
}

您可以根据需要自定义以下代码:

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;

    }
}

您可以根据需要自定义以下代码:

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;

    }
}

1年1个月不是2个月如果你不关心闰年,试试
/365
%365
。1年1个月不是2个月如果你不关心闰年,试试
/365
%365
。这与我提供更多解释的答案有什么不同?这与我提供更多解释的答案有什么不同?天哪。您知道,自Java 1.1(即7个主要版本)以来,就有人不推荐使用它了吗?请阅读关于代码的注释“//some data initilization for the sample”。仅用于样品制备和测试。对吧,那么??您是否建议使用已弃用10多年的API?如果您看到示例已更正,请更新您的投票。我不会。这是一个代码唯一的答案,因此,这不是一个好的和有益的答案。另外,您仍然使用不推荐的API。您应该尝试使您的贡献独特,而不仅仅是代码转储。堆栈溢出就是这样。请读。哦,上帝。您知道自从Java 1.1,即7个主要版本之前,就有人反对使用它吗?请阅读