Java 如何从字符串中获取经过的年数

Java 如何从字符串中获取经过的年数,java,android,date,calendar,Java,Android,Date,Calendar,我的字符串日期是1991年9月3日。我想知道这一天已经过去了多少年。例如23。如何使用日历或日期实现它 编辑: 我一直在尝试: private String parseVkBirthday(String birthdayString) { // 3.9.1991 SimpleDateFormat formatter = new SimpleDateFormat("d.M.yyyy"); String formattedDate = nul

我的字符串日期是1991年9月3日。我想知道这一天已经过去了多少年。例如23。如何使用日历或日期实现它

编辑:

我一直在尝试:

    private String parseVkBirthday(String birthdayString) {

        // 3.9.1991
        SimpleDateFormat formatter = new SimpleDateFormat("d.M.yyyy");
        String formattedDate = null;
        Calendar date = Calendar.getInstance();

        int year = 0;

        try {
            Date currentDate = new Date();
            Date birthdayDate = formatter.parse(birthdayString);

            Log.d(LOG_TAG, "year1 = " + currentDate.getTime() + " year2 = " + birthdayDate.getTime());

            long diff = currentDate.getTime() - birthdayDate.getTime();

            birthdayDate.setTime(diff);

            date.setTime(birthdayDate);

            year = date.get(Calendar.YEAR);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return "" + year;
    }
但它让我回到了1993年

答复:

解决此问题的方法有三种:

正如codeaholicguy所回答的,我们可以使用我喜欢的Android库

2正如Basil Bourque所回答的,我们可以使用库来使用Java8中的java.time类

我们可以使用java 8和java.time中的类

谢谢大家

Calendar mydate = new GregorianCalendar();
String mystring = "3.9.1991";
Date thedate = new SimpleDateFormat("d.m.yyyy", Locale.ENGLISH).parse(mystring);
mydate.setTime(thedate);
//breakdown

System.out.println("year   -> "+mydate.get(Calendar.YEAR));
图书馆的使用和维护,示例如下:

String pattern = "dd.MM.yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);

Date date = format.parse("3.9.1991");
System.out.println(date);
Period period = new Period(date.getTime(), (new Date()).getTime());
System.out.println(period.getYears());
图书馆的使用和维护,示例如下:

String pattern = "dd.MM.yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);

Date date = format.parse("3.9.1991");
System.out.println(date);
Period period = new Period(date.getTime(), (new Date()).getTime());
System.out.println(period.getYears());

Calendar.YEAR可用于从当前日期中添加或减去年份,与我们在日期中添加天数和月份的方式相同

示例程序:

import java.util.Calendar;

public class Years {

  public static void main(String[] args) {
    //create Calendar instance
    Calendar now = Calendar.getInstance();

    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));


    //add year to current date using Calendar.add method
    now.add(Calendar.YEAR,1);

    System.out.println("date after one year : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));

    //substract year from current date
    now =Calendar.getInstance();
    now.add(Calendar.YEAR,-100);
    System.out.println("date before 100 years : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));

  }
}

Calendar.YEAR可用于从当前日期中添加或减去年份,与我们在日期中添加天数和月份的方式相同

示例程序:

import java.util.Calendar;

public class Years {

  public static void main(String[] args) {
    //create Calendar instance
    Calendar now = Calendar.getInstance();

    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));


    //add year to current date using Calendar.add method
    now.add(Calendar.YEAR,1);

    System.out.println("date after one year : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));

    //substract year from current date
    now =Calendar.getInstance();
    now.add(Calendar.YEAR,-100);
    System.out.println("date before 100 years : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));

  }
}
基于2.8库:

// get the current year with @xrcwm's code
Calendar mydate = new GregorianCalendar();
String mystring = "3.9.1991";
Date thedate = new SimpleDateFormat("d.m.yyyy", Locale.ENGLISH).parse(mystring);
DateTime myDateTime = new DateTime(thedate.getTime()); // joda DateTime object

// get he current date
DateTime currentDateTime = new DateTime();

// get the years value
long years = Years.between(currentDateTime, myDateTime).getYears()
上面的代码应该为您提供正确的值。请注意,此代码可能有一些语法错误

作为旁注,Java 8有一个时间包,它似乎提供了更多相同的功能。

基于2.8库:

// get the current year with @xrcwm's code
Calendar mydate = new GregorianCalendar();
String mystring = "3.9.1991";
Date thedate = new SimpleDateFormat("d.m.yyyy", Locale.ENGLISH).parse(mystring);
DateTime myDateTime = new DateTime(thedate.getTime()); // joda DateTime object

// get he current date
DateTime currentDateTime = new DateTime();

// get the years value
long years = Years.between(currentDateTime, myDateTime).getYears()
上面的代码应该为您提供正确的值。请注意,此代码可能有一些语法错误

另外,Java8有一个时间包,它似乎提供了更多相同的功能。

Java.time Java8和更高版本中的新类取代了旧的Java.util.Date/.Calendar和SimpleTextFormat类

首先使用新的DateTimeFormatter类解析字符串。不要使用SimpleTextFormat。并阅读文档,因为新旧类之间的符号代码可能存在细微差异

获取今天的日期,以计算经过的年份。请注意,我们需要一个时区。时区对于确定日期至关重要。例如,巴黎的新的一天比蒙特勒尔的破晓要早

本课程将时间跨度视为与时间轴上的任何点无关的年、月和日数

between方法使用到日期时间处理常用的半开放方法。开始是包含的,而结束是独占的

java.time的默认格式遵循标准。如果希望日期时间值的字符串表示形式不同,请应用格式化程序

String input = "3.9.1991" ;

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d.M.yyyy") ;
LocalDate then = LocalDate.parse( input, formatter ) ;

ZoneId zone = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( zone ) ;  // Specify time zone to get your locality’s current date.

Period period = Period.between( then , today ) ;
int years = period.getYears() ;

System.out.println( "Between " + then + " and " + today + " is " + years + " years.");
1991-09-03和2015-07-09之间是23年

乔达时间 Android目前缺少Java8功能。因此,您不能使用java.time。除非项目a支持上面示例中使用的类,而b在Android上工作,否则我也不知道

或者,您可以使用激发java.time的第三方库。上述代码示例的Joda时间代码版本将非常类似。在本例中,java.time和Joda-time使用相似的类彼此并行。

java.time Java8和更高版本中的新类取代了旧的Java.util.Date/.Calendar和SimpleTextFormat类

首先使用新的DateTimeFormatter类解析字符串。不要使用SimpleTextFormat。并阅读文档,因为新旧类之间的符号代码可能存在细微差异

获取今天的日期,以计算经过的年份。请注意,我们需要一个时区。时区对于确定日期至关重要。例如,巴黎的新的一天比蒙特勒尔的破晓要早

本课程将时间跨度视为与时间轴上的任何点无关的年、月和日数

between方法使用到日期时间处理常用的半开放方法。开始是包含的,而结束是独占的

java.time的默认格式遵循标准。如果希望日期时间值的字符串表示形式不同,请应用格式化程序

String input = "3.9.1991" ;

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d.M.yyyy") ;
LocalDate then = LocalDate.parse( input, formatter ) ;

ZoneId zone = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( zone ) ;  // Specify time zone to get your locality’s current date.

Period period = Period.between( then , today ) ;
int years = period.getYears() ;

System.out.println( "Between " + then + " and " + today + " is " + years + " years.");
1991-09-03和2015-07-09之间是23年

乔达时间 Android目前缺少Java8功能。因此,您不能使用java.time。除非项目a支持上面示例中使用的类,而b在Android上工作,否则我也不知道


或者,您可以使用激发java.time的第三方库。上述代码示例的Joda时间代码版本将非常类似。在本例中,java.time和Joda time使用相似的类彼此并行。

哪个版本的java?将使用哪个版本的Java?将使用这段好代码,但它返回24。但我需要23个。我不知道为什么它会返回24…@Бцццццццццццццццццццц109。我将把它标为正确答案。但我认为还有更好的答案。不使用Joda时间图书馆。这是一个非常好的图书馆!我得到23=谢谢!这段代码很好,但它返回24。但我需要23个。我不知道为什么它会返回24…@БцццС

因为2015-1991=24,我更新了答案使用Joda时间计算年份差异谢谢,我会试试这个lirary。这似乎是尝试。我将把它标为正确答案。但我认为还有更好的答案。不使用Joda时间图书馆。这是一个非常好的图书馆!我得到23=谢谢!返回1991…不是23。返回1991…不是23。这个答案返回24。但我需要23个。这不是考虑期,如果有帮助,请投票表决。我能知道你为什么需要23块钱吗?因为正确答案是24,无论如何你可以在最后加上-1。因为2015年7月9日-1991年9月3日应该是23年。看看这个月。很抱歉,我不能回答,因为我没有15声誉=|这个答案返回24。但我需要23个。这不是考虑期,如果有帮助,请投票表决。我能知道你为什么需要23块钱吗?因为正确答案是24,无论如何你可以在最后加上-1。因为2015年7月9日-1991年9月3日应该是23年。看看这个月。很抱歉,我不能更新,因为我没有15个信誉=| A DateTime构造函数接受java.util.Date。因此,无需调用getTime方法.B,最好尽可能完全避免java.util.Date。Joda Time可以完成所有工作,包括解析输入字符串。因此,无需调用getTime方法.B,最好尽可能完全避免java.util.Date。Joda Time可以完成所有工作,包括解析输入字符串。感谢您分享关于java.Time=的知识,现在我在这里看到了解决问题的3种方法。我使用乔达时间图书馆。2使用Three-Ten Backport库。3使用Java 8和Java.time。@Бцццццццццццццц。对于Android来说,Joda Time确实有效,尽管有些人报告说,在Android上运行时,第一次调用Joda Time时,启动速度很慢,但不知道这是否仍然是真的,或者有多重要。Backport项目可能在Android上工作,也可能不工作,我不知道。最后,java.time肯定不会在Android上运行,因为它在2015-07年还不可用。我还没有在Android上尝试Backport。我认为应该行得通。我将尝试一下,稍后在这里写。感谢您分享关于java.time=的知识,现在我在这里看到了解决问题的3种方法。我使用乔达时间图书馆。2使用Three-Ten Backport库。3使用Java 8和Java.time。@Бцццццццццццццц。对于Android来说,Joda Time确实有效,尽管有些人报告说,在Android上运行时,第一次调用Joda Time时,启动速度很慢,但不知道这是否仍然是真的,或者有多重要。Backport项目可能在Android上工作,也可能不工作,我不知道。最后,java.time肯定不会在Android上运行,因为它在2015-07年还不可用。我还没有在Android上尝试Backport。我认为应该行得通。我会试试这个,稍后再写在这里。