如何将日历对象转换为即时消息



我有一个根据需要操作的Calendar对象,但将其转换为Instant并不能给我正确的结果:

Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(inputFiledate); // sets calendar time/date --> inputFiledate is 29-12-2015
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(inputFileHour)); -->inputFileHour is 5
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.HOUR_OF_DAY,3); // adds  hours that is now time is 29-12-2015 08:00:00
System.out.println("Date after manipulation "+cal.getTime()); -->Displays 
TimeZone tz = TimeZone.getTimeZone("UTC");
// set the time zone with the given time zone value 
// and print it
cal.setTimeZone(tz);
// Date date = cal.getTime(); // returns new date object, one hour in the future
Date d= cal.getTime();
System.out.println("DAte to Instant "+ d.toInstant()); 
System.out.println(" Calendar to Instant "+cal.toInstant());
System.out.println("Date after manipulation2 "+cal.getTime());

这是输出:

Date after manipulation Tue Dec 29 08:00:00 IST 2015
DAte to Instant 2015-12-29T02:30:00Z
Calendar to Instant 2015-12-29T02:30:00Z
Date after manipulation2 Tue Dec 29 08:00:00 IST 2015

需要将此日历对象转换为即时,但结果不正确2015-12-29T02:30:00Z其中,作为输出应为2015-12-29T08:00:00Z我哪里错了?

也尝试过用Zoned datetime,用Timezone,都没有成功。

日期没有时区。根据时差,我假设你使用的是印度时间(-5:30)。这只是相对于历元的时间,在每个时区都不同。

我建议您使用ZonedDateTime进行计算,而不是尝试从日历转换。

最新更新