如何使用simpledateformat将一年中的某一天作为整数?

时间:2018-04-07 02:43:20

标签: java date simpledateformat java-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 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);
    }

3 个答案:

答案 0 :(得分:3)

喜欢这个

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

答案 1 :(得分:3)

假设您使用的是Java 8+,您可以使用LocalDate类来解析它DateTimeFormatter

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-dd-yyyy");
System.out.println(LocalDate.parse("06-10-2008", fmt).getDayOfYear());

输出(根据要求)

162

答案 2 :(得分:0)

Calendar c = Calendar.getInstance();
c.setTime(date2);
System.out.println("Day of year = " + c.get(Calendar.DAY_OF_YEAR));