【问题标题】:How to get day of year as an integer with simpledateformat? [duplicate]如何使用simpledateformat将一年中的一天作为整数? [复制]
【发布时间】:2018-04-07 21:24:55
【问题描述】:

我有一个简单的程序,要求用户以 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);
    }

【问题讨论】:

标签: java simpledateformat date


【解决方案1】:

假设您使用的是 Java 8+,您可以使用 LocalDate 类将其解析为 DateTimeFormatter 之类的

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

输出(按要求)

162

【讨论】:

  • 如果您将ThreeTen Backport 添加到您的项目中,这也将在Java 6 和7 中很好地工作。在(较旧的)Android 上使用相同的 Android 版本:ThreeTenABP
【解决方案2】:

这样

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

【讨论】:

【解决方案3】:
Calendar c = Calendar.getInstance();
c.setTime(date2);
System.out.println("Day of year = " + c.get(Calendar.DAY_OF_YEAR));   

【讨论】:

猜你喜欢
  • 2015-01-24
  • 2012-06-17
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
  • 2015-12-27
  • 1970-01-01
  • 2020-01-29
  • 2020-10-24
相关资源
最近更新 更多