Java 8下将dd-MMM-yy格式日期转为带指定时分的IST时区日期求助
解决方案
Java 8 推荐使用java.time包下的新日期API替代旧的java.util.Date和SimpleDateFormat,既能满足需求,又能避开废弃方法的使用。
实现步骤
- 解析原始日期字符串:用线程安全的
DateTimeFormatter解析12-FEB-23格式的字符串,得到LocalDate对象。 - 指定时间与时区:将
LocalDate转为包含目标时间(05:30:00)的LocalDateTime,再绑定印度标准时间(IST,对应时区ID为Asia/Kolkata)得到ZonedDateTime。 - 兼容旧Date类型(若需):如果必须输出
Date类型,可通过ZonedDateTime转换得到,全程无需使用废弃的setHours方法。
完整代码示例
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; public class DateConversion { public static void main(String[] args) { // 原始日期字符串 String oldDateStr = "12-FEB-23"; // 定义解析格式 DateTimeFormatter parser = DateTimeFormatter.ofPattern("dd-MMM-yy"); // 解析为LocalDate LocalDate localDate = LocalDate.parse(oldDateStr, parser); // 设置目标时间为05:30:00,转换为LocalDateTime LocalDateTime localDateTime = localDate.atTime(5, 30, 0); // 绑定印度标准时间时区 ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Kolkata")); // 若需转换为java.util.Date类型(兼容旧代码场景) Date newDate = Date.from(zonedDateTime.toInstant()); // 输出结果,格式与需求一致 System.out.println("newDate = " + newDate); } }
特殊场景处理(日期跨天)
如果输入12-FEB-23需要输出Sun Feb 13 05:30:00 IST 2023(时区导致的日期偏移),只需将原始日期视为UTC时间再转换为IST:
// 将原始日期解析为UTC时区的起始时间 ZonedDateTime utcDateTime = localDate.atStartOfDay(ZoneId.of("UTC")); // 转换为IST时区 ZonedDateTime istDateTime = utcDateTime.withZoneSameInstant(ZoneId.of("Asia/Kolkata")); // 覆盖为目标时间 istDateTime = istDateTime.withHour(5).withMinute(30).withSecond(0);
内容的提问来源于stack exchange,提问作者chand
相关产品推荐
相关产品推荐

