如何将Calendar对象设为当前日期+指定HH:mm:ss格式时间
解决思路:保留当前日期,设置指定时分秒
当然可以这么做!这刚好能解决你遇到的问题——之前用SimpleDateFormat解析时间字符串时,因为只指定了HH:mm:ss格式,所以解析出的Date默认会用1970年1月1日作为日期部分,但我们只需要它的时分秒信息就行,具体步骤如下:
方法一:用Calendar API(兼容Java 7及以下)
- 先获取包含当前完整日期时间的Calendar对象
Calendar targetCalendar = Calendar.getInstance();
- 解析你的时间字符串,得到对应的时间Date对象(日期部分忽略即可)
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); Date timeOnlyDate = timeFormat.parse("16:25:00"); // 替换成你的目标时间字符串
- 把时间Date转成临时Calendar,提取时分秒毫秒,再设置到目标Calendar里
Calendar tempCalendar = Calendar.getInstance(); tempCalendar.setTime(timeOnlyDate); // 替换目标Calendar的时分秒毫秒,保留原有的年、月、日 targetCalendar.set(Calendar.HOUR_OF_DAY, tempCalendar.get(Calendar.HOUR_OF_DAY)); targetCalendar.set(Calendar.MINUTE, tempCalendar.get(Calendar.MINUTE)); targetCalendar.set(Calendar.SECOND, tempCalendar.get(Calendar.SECOND)); targetCalendar.set(Calendar.MILLISECOND, tempCalendar.get(Calendar.MILLISECOND));
这样targetCalendar就拥有当前的年、月、日,以及你指定的时分秒了。
方法二:Java 8+ 推荐使用新的日期时间API(更优雅且线程安全)
如果你用的是Java 8及以上,更推荐使用java.time包下的API,避免旧API的线程安全问题:
// 获取当前日期 LocalDate today = LocalDate.now(); // 解析指定的时间字符串 LocalTime specifiedTime = LocalTime.parse("16:25:00"); // 组合成完整的日期时间 LocalDateTime combinedDateTime = LocalDateTime.of(today, specifiedTime); // 如果需要转换成Calendar对象(兼容旧代码场景) ZonedDateTime zonedDateTime = combinedDateTime.atZone(ZoneId.systemDefault()); Calendar calendar = Calendar.getInstance(); calendar.setTime(Date.from(zonedDateTime.toInstant()));
内容的提问来源于stack exchange,提问作者reibuehl
相关产品推荐
相关产品推荐

