为什么java';使用SimpleTimeZone时,s SimpleDateFormat从我的UTC日期减去1秒
有人能解释一下为什么在使用SimpleTimeZone设置时区时,SimpleDataFormat会将解析的日期减去1秒 这是jdk错误吗为什么java';使用SimpleTimeZone时,s SimpleDateFormat从我的UTC日期减去1秒,java,simpledateformat,Java,Simpledateformat,有人能解释一下为什么在使用SimpleTimeZone设置时区时,SimpleDataFormat会将解析的日期减去1秒 这是jdk错误吗 import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.SimpleTimeZone; import java.util.TimeZone; public class SimpleDateFormatTest { public sta
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
public class SimpleDateFormatTest {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(format.parse("2016-02-24T17:31:00Z"));
// prints Wed Feb 24 17:31:00 UTC 2016
format.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
System.out.println(format.parse("2016-02-24T17:31:00Z"));
// Wed Feb 24 17:30:59 UTC 2016
}
}
的值实际上是2,因此使用两毫秒的偏移量构造SimpleTimeZone
:
/**
* Constant for a mode of start or end time specified as UTC. European
* Union rules are specified as UTC time, for example.
* @since 1.4
*/
public static final int UTC_TIME = 2;
/**
* Constructs a SimpleTimeZone with the given base time zone offset from GMT
* and time zone ID with no daylight saving time schedule.
*
* @param rawOffset The base time zone offset in milliseconds to GMT.
* @param ID The time zone name that is given to this instance.
*/
public SimpleTimeZone(int rawOffset, String ID)
{
this.rawOffset = rawOffset;
setID (ID);
dstSavings = millisPerHour;
}
:
结果:
1456335060000
1456335059998
您未正确使用构造函数
SimpleTimeZone
的构造函数定义为:
public static final int UTC_TIME = 2;
public SimpleTimeZone(int-rawOffset,
字符串ID)
构造一个SimpleTimeZone,该SimpleTimeZone具有从GMT开始的给定基本时区偏移量和不带日光的时区ID
节省时间安排
参数:
rawOffset
-基准时区
偏移量(毫秒)到GMT
ID
-给定的时区名称
对这种情况
因此,构造函数的第一个参数是您正在创建的时区与GMT的差值,以毫秒为单位
没有理由在此处使用任何常量标准时间
、UTC时间
或墙时间
。这不是使用它们的地方。但是,由于这些常量的类型为int
,并且rawOffset
参数的类型为int
,因此Java不会阻止您将这些常量错误地传递给构造函数
在Java源代码中,此常量定义为:
public static final int UTC_TIME = 2;
那么,当你打电话时,你实际上在做什么
new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC")
表示“请创建一个距离GMT 2毫秒的时区,并称之为‘UTC’”。我很确定这不是你想要达到的。这是一个自定义时区,与UTC有点不同,并且在输出中将此差异四舍五入到整秒钟