java 从字符串中获取时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9852812/
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
Getting time from String
提问by Eugene Shmorgun
My Java code must get string "HH:MM" from console and needs to operate with it. is there possible to parse such time from string in order to add, for example,2 hours.
我的 Java 代码必须从控制台获取字符串 "HH:MM" 并需要对其进行操作。是否可以从字符串中解析这样的时间以添加,例如,2 小时。
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter some time:");
String enteredTime = in.readLine();
// here I want to get time in some variable
Thanks!
谢谢!
As result I have to get three dates and define is there three date between another dates . I understand that I can split string on parts and work with their, but I'm lloking for simple way to operate with such times.
结果我必须得到三个日期并定义另一个日期之间是否有三个日期。我知道我可以在零件上拆分字符串并使用它们,但是我正在寻找一种简单的方法来处理这种情况。
I found good solution:
我找到了很好的解决方案:
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");
try {
Date userDate = parser.parse(someOtherDate);
if (userDate.after(ten) && userDate.before(eighteen)) {
...
}
} catch (ParseException e) {
// Invalid date was entered
}
回答by user unknown
sdf = new java.text.SimpleDateFormat ("HH:mm");
sdf.parse ("13:47");
回答by nansen
I understand you want to do some date arithmetics like adding durations to dates. Then you should definitely use joda timeinstead of java.util.Date and Calendar.
我知道您想做一些日期算术,例如为日期添加持续时间。那么你绝对应该使用joda 时间而不是 java.util.Date 和 Calendar。
Joda gives you Period and Duration entities and a nice and readeable API.
Joda 为您提供 Period 和 Duration 实体以及一个漂亮且可读的 API。