1. 问题与试验
Android官方API提供了一个获取当前系统时间的方法:
System.currentTimeMillis()
官方文档的说明:
long currentTimeMillis ()
Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
See the description of the class Date for a discussion of slight discrepancies that may arise between “computer time” and coordinated universal time (UTC).
这个API被广泛用于获取时间戳计时。同时,Android支持多时区。那么就引出一个问题,在切换时区的时候(随网络自动切换或者手动切换,同时不手动改变手机时间),这个时间戳的值是否是不受影响地持续自增?时区变化会导致当前系统时间随时差而变,这个变化是如何实现的?
先拿一个最简单的测试程序来试验:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
test();
}
});
}
private void test() {
Log.i("TEST_ZONE", "" + System.currentTimeMillis());
}
}
点击Button取时间戳打log出来。两次取时间戳,中间切换一次时区:
08-10 09:52:56.087 21629 21629 I TEST_ZONE: 1502329976087
08-10 03:53:19.125 21629 21629 I TEST_ZONE: 1502329999125
可以看到时间戳是在正常地增长。看起来应该是在标准化时间的计算上处理的不同时区时间转换。