使用 Scanner 在 Java 中读取日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23491255/
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
Read date in Java with Scanner
提问by HpdsbuΖt
Well, i'm trying to read a string with scanner in the same line. For exapme ,i want to read: Monday 12 December 2013 and this needs to be put in a String variable so as to help me print it.
好吧,我正在尝试在同一行中使用扫描仪读取字符串。例如,我想阅读:2013 年 12 月 12 日星期一,这需要放入一个字符串变量中以帮助我打印它。
In my code there is this:
在我的代码中有这样的:
sale.setDate(sc.next());
with the command sc.next()
i can't put a date in the form i mentioned but only in a form like: mmddyy or mm/dd/yyyy
使用该命令,sc.next()
我不能以我提到的形式输入日期,而只能以如下形式输入:mmddyy 或 mm/dd/yyyy
How can i read a whole string like "Monday 12 December 2013 " ?
我怎样才能读取像“2013 年 12 月 12 日星期一”这样的整个字符串?
There is a confusion for me about sc.next sc.nextLine etc..
我对 sc.next sc.nextLine 等感到困惑。
回答by subash
Try this..
尝试这个..
public void readDate() throws Exception{
String dateFormat = "dd/MM/yyyy";
Scanner scanner = new Scanner(System.in);
setDate(new SimpleDateFormat(dateFormat).parse(scanner.nextLine()));
}
public void setDate(Date date){
// do stuff
}
chage the dateFormat as you want..
根据需要更改 dateFormat ..
回答by niiraj874u
You have to use nextLine to fetch words with intermediate spaces.
您必须使用 nextLine 来获取带有中间空格的单词。
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
next() 只能读取输入直到空格。它无法读取由空格分隔的两个单词。此外,next() 在读取输入后将光标置于同一行。
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
nextLine() 读取输入,包括单词之间的空格(即,它读取到行尾 \n)。读取输入后,nextLine() 将光标定位在下一行。
Scanner sc=new Scanner(System.in);
System.out.println("enter string for c");
String c=sc.next();
System.out.println("c is "+c);
System.out.println("enter string for d");
String d=sc.next();
System.out.println("d is "+d);
OUTPUT:
输出:
enter string for c
abc def
c is abc
enter string for d
d is defabc def|
in the first case abc |def //cursor stays after c
在第一种情况下 abc |def //光标停留在 c 之后
in the second case abc def| //cursor stays after for
在第二种情况下 abc def| //光标停留在for
回答by user1121883
For scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.htmlThe next() and hasNext() methods first skip any input that matches the delimiter pattern, and then attempt to return the next token. nextLine advances this scanner past the current line and returns the input that was skipped.
对于扫描仪:http: //docs.oracle.com/javase/7/docs/api/java/util/Scanner.htmlnext() 和 hasNext() 方法首先跳过与分隔符模式匹配的任何输入,然后尝试返回下一个令牌。nextLine 将此扫描器推进到当前行并返回被跳过的输入。
Use a date DateFormat to parse string to date; I suppose setDate expects a Date
使用日期 DateFormat 将字符串解析为日期;我想 setDate 需要一个日期
Scanner scanner = new Scanner("Monday 12 December 2013,a, other fields");
scanner.useDelimiter(",");
String dateString = scanner.next();
//System.out.println(dateString);
DateFormat formatter = new SimpleDateFormat("EEEE dd MMM yyyy");
Date date = formatter.parse(dateString);
//System.out.println(date);
sale.setDate(sc.next());
回答by Mohit Miglani
Even i faced the same issue but after that able to resolve with below mentioned code. Hope it helps.
即使我也遇到了同样的问题,但之后可以使用下面提到的代码解决。希望能帮助到你。
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 AxelH
I found this question interesting but there is not a fully correct answer, so here is a simple solution to easily read and parse a Date
form the Scanner
.
我发现这个问题有意思,但还没有一个完全正确的答案,所以这里是一个简单的解决方案可以轻松地阅读和解析Date
的形式Scanner
。
The best approch would be to create a method that would do it for you, since Scanner
is final, we can only do a toolbox instead of a subclass. But this would be easy to use :
最好的方法是创建一个方法来为你做这件事,因为Scanner
是最终的,我们只能做一个工具箱而不是一个子类。但这很容易使用:
public static Date readDate(Scanner sc, String format){
return new SimpleDateFormat(format).parse(sc.nextLine());
}
This would accept the format and the Scanner, don't manage it here because it would be messy to open a Scanner
without closing it (but if you close it, you can't open it again).
这将接受格式和扫描仪,不要在这里管理它,因为打开 aScanner
而不关闭它会很麻烦(但是如果关闭它,则无法再次打开它)。
Scanner sc = new Scanner(System.in);
ToolBox.readDate(sc, "YYYY-MM-DD");
ToolBox.readDate(sc, "YYYY-MM-DD HH:mm:ss");
ToolBox.readDate(sc, "YYYY-MM-DD");
sc.close();
This could be improved by not recreating a SimpleDateFormat
each time but a Scanner is not called that much (you are limit by the user inputs) so this is not that important.
这可以通过不SimpleDateFormat
每次都重新创建来改进,但是扫描器并没有被调用那么多(您受到用户输入的限制)所以这不是那么重要。
回答by Joshua Biggs
Another way to do this is by utilizing LocalDateTime
and DateTimeFormatter
from Java 8. Found this example here:
另一种方法是利用LocalDateTime
和DateTimeFormatter
来自 Java 8。在这里找到这个例子:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm:ss.SSS);
LocalDateTime dateTime = LocalDateTime.parse(s.next(), formatter);
System.out.println(dateTime.format(formatter));
Check the link for an in-depth explanation!
检查链接以获得深入的解释!