在我的代码中,我希望从日期格式中获取单个数字,以便将它们用作int值:
@carbon.super
我还希望一些用户输入一次性定义日,月和年,如果可能的话:
public static final String DATE_FORMAT = "dd.MM.yyyy";
public int age()
{
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
// How to convert to int?
int currentnDay = ?;
int currentMonth = ?;
int currentYear = ?;
}
我希望你可以帮助我,以前我做的都是单独的,但代码很大,我认为如果我可以这样做那就更漂亮..
更新:好的我现在正在做这样的输入:
private Date dateOfPublication;
public void input()
{
Scanner scn = new Scanner( System.in );
System.out.print( "Please enter dateOfPublication: " );
// How to setup input for this?
}
感谢您的帮助!
答案 0 :(得分:1)
看一下Java 8的新Time API(如果你真的被卡住了,还是JodaTime或Calendar
)
LocalDate ld = LocalDate.parse("16.10.2015", DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue());
System.out.println(ld.getYear());
哪个输出
2015-10-16
16
10
2015
现在,您可以简单地要求用户输入给定格式的日期并尝试解析结果,如果解析失败,您可以重新提示它们
例如......
Scanner input = new Scanner(System.in);
LocalDate ld = null;
do {
System.out.print("Please enter date in " + DATE_FORMAT + " format: ");
String value = input.nextLine();
try {
ld = LocalDate.parse(value, DateTimeFormatter.ofPattern(DATE_FORMAT));
} catch (Exception e) {
System.err.println(value + " is not a valid date for the format of " + DATE_FORMAT);
}
} while (ld == null);
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue()); // Is probably 0 indexed
System.out.println(ld.getYear());
答案 1 :(得分:0)
您可以使用:
dateFormat.format(today).split("\\.");
代码:
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
String[] dateArr = dateFormat.format(today).split("\\.");
int currentnDay = Integer.parseInt(dateArr[0]);
int currentMonth = Integer.parseInt(dateArr[1]);
int currentYear = Integer.parseInt(dateArr[2]);
<强> IdeOne Example 强>
答案 2 :(得分:0)
首先,您必须解析输入字符串 日历数据类型对于日期时间处理更灵活。这是一个显示日期/日历操作的示例。
Date date;
Calendar c;
// Get the current date
c = Calendar.getInstance();
System.out.println("Current Calendar:" + c.getTime().toString());
int currentnDay = c.get(Calendar.DATE);
int currentMonth = c.get(Calendar.MONTH);
int currentYear = c.get(Calendar.YEAR);
System.out.println(String.format("Current Values: %d/%d/%d",
currentnDay, currentMonth, currentYear));
String DATE_FORMAT = "dd.MM.yyyy";
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
date = dateFormat.parse("11.10.1981");
System.out.println("Modified Date:" + date.toString());
// reset Calendar
c = Calendar.getInstance();
// set date to the calendar
c.setTimeInMillis(date.getTime());
currentnDay = c.get(Calendar.DATE);
currentMonth = c.get(Calendar.MONTH);
currentYear = c.get(Calendar.YEAR);
System.out.println(String.format("Modified Values: %d/%d/%d",
currentnDay, currentMonth, currentYear));
这是示例的输出。
当前日历:2015年10月15日星期五20:22:59
当前价值:15/9/2015
修改日期:Sun Oct 11 00:00:00 EDT 1981
修改后的值:1981年11月9日