Java 如何使用SimpleDataFormat将一年中的某一天作为整数获取?

Java 如何使用SimpleDataFormat将一年中的某一天作为整数获取?,java,simpledateformat,date,Java,Simpledateformat,Date,我有一个简单的程序,要求用户以MM-dd-yyyy格式输入日期。如何从该输入中获取一年中的哪一天?例如,如果用户输入“06-10-2008”,考虑到这是闰年,一年中的第162天将是闰年 以下是我目前的代码: System.out.println("Please enter a date to view (MM/DD/2008):"); String date = sc.next(); SimpleDateFormat dateFormat = new Simp

我有一个简单的程序,要求用户以MM-dd-yyyy格式输入日期。如何从该输入中获取一年中的哪一天?例如,如果用户输入“06-10-2008”,考虑到这是闰年,一年中的第162天将是闰年

以下是我目前的代码:

System.out.println("Please enter a date to view (MM/DD/2008):");

        String date = sc.next();

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
        Date date2=null;
        try {
            //Parsing the String
            date2 = dateFormat.parse(date);
        } catch (ParseException e) {                
            System.out.println("Invalid format, please enter the date in a MM-dd-yyyy format!");
            continue;
        } //End of catch
        System.out.println(date2);
    }
像这样

Calendar cal = Calendar.getInstance();
cal.setTime(date2); //Assuming this is date2 variable from your code snippet
int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);

假设您使用的是Java8+,您可以使用类来用类似的

产出(按要求)


如果添加到项目中,这在Java6和Java7中也能很好地工作。在(较旧的)Android上使用相同的Android版本:。我建议您避免使用
SimpleDataFormat
类。它不仅是出了名的麻烦,还有
日期
它也早已过时。今天,我们在.FYI中有了更好的功能,像、
java.text.SimpleDateFormat
这样麻烦的旧日期时间类现在被java 8和更高版本中内置的类所取代。请参见.FYI,诸如和
java.text.simpleDataFormat
之类的旧日期时间类现在已被java 8及更高版本中内置的类所取代。看见
Calendar cal = Calendar.getInstance();
cal.setTime(date2); //Assuming this is date2 variable from your code snippet
int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-dd-yyyy");
System.out.println(LocalDate.parse("06-10-2008", fmt).getDayOfYear());
162