如何使用 SimpleDateFormat 仅解析日期
我想解析用户给定的日期,但具有特定的格式:一周的日期名称。
到目前为止,这就是我所做的:
SimpleDateFormat format = new SimpleDateFormat("E", Locale.ENGLISH);
try {
Date date = format.parse ("Friday");
Calendar calendar = format.getCalendar();
calendar.add(Calendar.WEEK_OF_YEAR, 1);
return calendar.getTime();
}
catch (ParseException pe) {
return null;
}
但这返回了我:
2 janv. 1970 00:00:00
我希望它返回我未来的星期五(在我们的游戏中时光倒流中,2011 年 11 月 4 日
)
我该怎么办?
I'd like to parse given date by user but with a specific format : the day name of the week.
So far, here's what I did :
SimpleDateFormat format = new SimpleDateFormat("E", Locale.ENGLISH);
try {
Date date = format.parse ("Friday");
Calendar calendar = format.getCalendar();
calendar.add(Calendar.WEEK_OF_YEAR, 1);
return calendar.getTime();
}
catch (ParseException pe) {
return null;
}
But this returns me :
2 janv. 1970 00:00:00
I'd like it to return me the future friday (in our timelapse, 4 nov. 2011
)
How can I do ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅解析日期,将其放入
Calendar
中,以便您可以找到星期几,然后根据当前日期创建另一个日历,以便您可以设置星期几:请注意,这不一定会将其置于未来 - 它将设置当前周内的日期。因此,如果您想确保它确实是在未来,您可能需要在之后添加一周:(
如果当前星期几与解析的星期几相同,您应该检查您想要什么行为......
) ,我个人建议使用 Joda Time 来处理 Java 中所有重要的日期和时间工作。这是一个更好的 API。
Parse just the day, put that into a
Calendar
so that you can find the day of the week, then create another calendar based on the current date so that you can set the day of week:Note that that won't necessarily put it into the future - it'll set the day within the current week. So you may want to add a week afterwards, if you want to ensure that it's really in the future:
(You should check what behaviour you want if the current day of week is the same as the parsed one...)
As an aside, I'd personally recommend using Joda Time for all serious date and time work in Java. It's a much nicer API.
获取
Calendar.getInstance()
并将DAY_OF_WEEK
设置为format.getCalendar()
的值。您需要检查当前星期的日期是否在星期五之后。在这种情况下 - 增加周数。Get a
Calendar.getInstance()
and simpyl set theDAY_OF_WEEK
to the value of theformat.getCalendar()
. You'd need to make a check if the current date of week is after Friday. In that case - increment the week.