如何在java中将日期设置为输入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27580655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set a date as input in java?
提问by user3159060
Is there any direct way to set a date to a variable but as an input? I mean that i don't know the date at design time, the user should give it. I tried the following code but it doesn't work: Calendar myDate=new GregorianCalendar(int year, int month , int day);
有没有直接的方法可以将日期设置为变量但作为输入?我的意思是我不知道设计时的日期,用户应该给它。我尝试了以下代码,但它不起作用: Calendar myDate=new GregorianCalendar(int year, int month , int day);
回答by sitakant
Try the following code. I am parsing the entered String to make a Date
试试下面的代码。我正在解析输入的字符串以生成日期
// 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);
回答by Vikas
I have modified @SK08 answer and created a method which takes year, month and date as input from the user and returns date.
我修改了@SK08 答案并创建了一个方法,该方法将年、月和日期作为用户的输入并返回日期。
Scanner scanner = new Scanner(System.in);
String str[] = {"year", "month", "day" };
String date = "";
for(int i=0; i<3; i++) {
System.out.println("Enter " + str[i] + ": ");
date = date + scanner.next() + "/";
}
date = date.substring(0, date.length()-1);
System.out.println("date: "+ date);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date parsedDate = null;
try {
parsedDate = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return parsedDate;
回答by Basil Bourque
tl;dr
tl;博士
LocalDate.of( 2026 , 1 , 23 ) // Pass: ( year , month , day )
java.time
时间
Some other Answers are correct in showing how to gather input from the user, but use the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
其他一些答案在展示如何从用户那里收集输入方面是正确的,但使用了现在遗留的麻烦的旧日期时间类,由 java.time 类取代。
LocalDate
LocalDate
For a date-only value without time-of-day and without time zone, use the LocalDate
class.
对于没有时间和时区的仅日期值,请使用LocalDate
该类。
LocalDate ld = LocalDate.of( 2026 , 1 , 23 );
Parse your input strings as integers as discussed here: How do I convert a String to an int in Java?
将您的输入字符串解析为整数,如下所述: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 );
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android, the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- java.time 类的更高版本的 Android 捆绑实现。
- 对于早期的 Android,ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
回答by Mohit Miglani
This should work fine and you can validate the date as well using setlenient function-
这应该可以正常工作,您也可以使用 setlenient 功能验证日期-
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
public class Datinput {
public static void main(String args[]) {
int n;
ArrayList<String> al = new ArrayList<String>();
Scanner in = new Scanner(System.in);
n = in.nextInt();
String da[] = new String[n];
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false);
Date date[] = new Date[n];
in.nextLine();
for (int i = 0; i < da.length; i++) {
da[i] = in.nextLine();
}
for (int i = 0; i < da.length; i++) {
try {
date[i] = sdf.parse(da[i]);
} catch (ParseException e) {
e.printStackTrace();
}
}
in.close();
}
}
回答by Ibrahim Yesilay
This is working I tried!
这是我试过的工作!
package javaapplication2;
//@author Ibrahim Yesilay
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) throws ParseException {
Scanner giris = new Scanner(System.in);
System.out.println("gün:");
int d = giris.nextInt();
System.out.println("ay:");
int m = giris.nextInt();
System.out.println("yil:");
int y = giris.nextInt();
String tarih;
tarih = Integer.toString(d) + "/" + Integer.toString(m) + "/" + Integer.toString(y);
System.out.println("Tarih : " + tarih);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date girilentarih = null;
girilentarih = dateFormat.parse(tarih);
System.out.println(dateFormat.format(girilentarih));
}
}