如何使用 simpledateformat 将年中的某一天作为整数获取?
How to get day of year as an integer with simpledateformat?
我有一个简单的程序,要求用户以 MM-dd-yyyy 格式输入日期。我怎样才能从这个输入中得到一年中的哪一天?例如,如果用户输入“06-10-2008”,考虑到今年是闰年,那么一年中的第 162 天就是第 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 c = Calendar.getInstance();
c.setTime(date2);
System.out.println("Day of year = " + c.get(Calendar.DAY_OF_YEAR));
像这样
Calendar cal = Calendar.getInstance();
cal.setTime(date2); //Assuming this is date2 variable from your code snippet
int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);
假设您使用的是 Java 8+,您可以使用 LocalDate
class to parse it with a DateTimeFormatter
之类的
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-dd-yyyy");
System.out.println(LocalDate.parse("06-10-2008", fmt).getDayOfYear());
输出(按要求)
162
我有一个简单的程序,要求用户以 MM-dd-yyyy 格式输入日期。我怎样才能从这个输入中得到一年中的哪一天?例如,如果用户输入“06-10-2008”,考虑到今年是闰年,那么一年中的第 162 天就是第 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 c = Calendar.getInstance();
c.setTime(date2);
System.out.println("Day of year = " + c.get(Calendar.DAY_OF_YEAR));
像这样
Calendar cal = Calendar.getInstance();
cal.setTime(date2); //Assuming this is date2 variable from your code snippet
int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);
假设您使用的是 Java 8+,您可以使用 LocalDate
class to parse it with a DateTimeFormatter
之类的
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-dd-yyyy");
System.out.println(LocalDate.parse("06-10-2008", fmt).getDayOfYear());
输出(按要求)
162