将时间解析到日历中而不丢失日期部分 [英] Parse Time into Calendar without losing Date part
问题描述
我需要在一个Calendar
Java对象中存储一个日期/时间,该日期/时间包括今天的日期以及从一个以HH:mm:ss
格式的字符串解析的时间.
I need to store in a Calendar
Java object a date/time consisting of today's date plus a time parsed from a string in a HH:mm:ss
format.
我尝试创建一个新的GregorianCalendar
并使用setTime()
对其进行初始化,并调用SimpleDateFormat
的parse()方法,但随后我发现parse()
返回一个Date
对象,该对象带有正确的解析时间,但日期为1970年1月1日.
I tried creating a new GregorianCalendar
and using setTime()
to initialize it with the result of calling a SimpleDateFormat
's parse() method but then I noticed that parse()
returns me a Date
object with the correct parsed time but with the date of Jan 1, 1970.
例如:
String time = "23:32";
String timeFmt = new SimpleDateFormat("HH:mm");
Calendar todaysTime = new GregorianCalendar();
todaysTime.setTime(timeFmt.parse(time));
System.out.println(todaysTime.getTime());
打印:Thu Jan 01 11:32:00 CST 1970
我所期望的是:Wed 03 11:32:00 CST 2015
Prints: Thu Jan 01 11:32:00 CST 1970
What I expected was: Wed 03 11:32:00 CST 2015
我只能看到一种选择:用今天的日期创建第二个GregorianCalendar
,然后通过setYear()
,setMonth()
和setDayOfMonth()
手动将年,月和日设置为todaysTime
,但我希望有一种更优雅的方法.
I can only see one alternative: Create a second GregorianCalendar
with todays date and then set the year, month and day manually into todaysTime
via setYear()
, setMonth()
and setDayOfMonth()
but I hope there is a more elegant way to do that.
您能帮我寻找一种更好的方法来解析解析为Date
对象的时间部分而又不丢失日期部分吗?
Can you help me look for a better way to parse the time part parsed into a Date
object without losing the date part?
推荐答案
您可以执行以下操作:
Date parsedDate = SimpleDateFormat.getInstance().parse(time);
Calendar instance = Calendar.getInstance();
instance.setTime( parsedDate );
Calendar result = Calendar.getInstance();
result.set( Calendar.HOUR_OF_DAY, instance.get( Calendar.HOUR_OF_DAY ) );
result.set( Calendar.MINUTE, instance.get( Calendar.MINUTE ) );
这篇关于将时间解析到日历中而不丢失日期部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!