如何将Calendar对象转换为Instant?

时间:2015-12-30 13:15:59

标签: java date datetime java-8

我根据自己的需要操作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

需要将此Calendar对象转换为即时,但它给出的结果不正确2015-12-29T02:30:00Z 输出应在2015-12-29T08:00:00Z 我哪里错了?

还尝试使用Zoned datetimeTimezone,徒劳无功。

1 个答案:

答案 0 :(得分:1)

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

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