use*_*060 5 java calendar date gregorian-calendar
有没有直接的方法来设置变量的日期,但作为输入?我的意思是我不知道设计时的日期,用户应该给它.我尝试了以下代码,但它不起作用:Calendar myDate = new GregorianCalendar(int year,int month,int day);
请尝试以下代码.我正在解析输入的字符串以生成日期
// To take the input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Date ");
String date = scanner.next();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date date2=null;
try {
//Parsing the String
date2 = dateFormat.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(date2);
Run Code Online (Sandbox Code Playgroud)
LocalDate.of( 2026 , 1 , 23 ) // Pass: ( year , month , day )
Run Code Online (Sandbox Code Playgroud)
其他一些答案在展示如何从用户那里收集输入方面是正确的,但使用了现在遗留的麻烦的旧日期时间类,由 java.time 类取代。
LocalDate
对于没有时间和时区的仅日期值,请使用LocalDate
该类。
LocalDate ld = LocalDate.of( 2026 , 1 , 23 );
Run Code Online (Sandbox Code Playgroud)
将您的输入字符串解析为整数,如下所述:How do I convert a String to an int in Java?
int y = Integer.parseInt( yearInput );
int m = Integer.parseInt( monthInput ); // 1-12 for January-December.
int d = Integer.parseInt( dayInput );
LocalDate ld = LocalDate.of( y , m , d );
Run Code Online (Sandbox Code Playgroud)
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
从哪里获得 java.time 类?
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
归档时间: |
|
查看次数: |
69892 次 |
最近记录: |