时间戳表示从纪元起经过的时间的“绝对”值.例如,您的currentTimeUTCinSeconds代表自Unix纪元以来的秒数(1970年1月1日至00:00Z,或1970年1月1日,UTC午夜). Java API通常以自纪元以??来的毫秒数工作.
但是概念是相同的-这些值是“绝对的”:无论世界在哪里,它们对于世界上的每个人都是相同的.如果世界上不同地区(在不同时区)的2个人同时获得当前时间戳,那么他们都将获得相同的号码.
所不同的是,在不同的时区,此相同的数字表示不同的本地日期和时间.
例如,您使用的时间戳对应于UTC 2017年9月7日08:55:56,其值为1504774556(自纪元以来的秒数).该数字对应于伦敦的09:55,卡拉奇的13:55,东京的17:55等.更改此数字将更改每个人的当地时间-无需进行操作.
如果要获取表示此瞬间的java.util.Date,请执行以下操作:
int currentTimeUTCinSeconds = 1504774556;
// cast to long to not lose precision
Date date = new Date((long) currentTimeUTCinSeconds * 1000);
该日期将保留值1504774556000(自纪元以来的毫秒数).该值对应于伦敦的09:55,卡拉奇的13:55和东京的17:55.
但是打印此日期会将其转换为您的JVM默认时区(here是有关Date :: toString()方法的行为的很好的解释).当您执行“ Date Time:”日期时,它隐式调用toString()方法,结果是将日期转换为默认时区.
如果您希望日期采用特定格式和特定??时区,则需要一个SimpleDateFormat.仅打印日期(使用System.out.println或通过记录日期)将不起作用:您无法更改日期对象本身的格式,因为日期为has no format.
我还使用java.util.Locale来指定月份和星期几必须为英文.如果您不指定语言环境,它将使用系统默认值,并且不能保证始终使用英语(而且即使在运行时也可以更改,因此最好始终指定语言环境):
// use the same format, use English for month and day of week
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z (zzzz)", Locale.ENGLISH);
// set the timezone I want
sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
// format the date
System.out.println(sdf.format(date));
输出将是:
Thu Sep 07 2017 09:55:56 GMT+0100 (British Summer Time)
请注意,我不需要操纵时间戳记值.我不使用google API,但我认为它们的解释太混乱了,上面的代码以较少的复杂性实现了相同的结果.
在您的特定情况下,您可以执行以下操作:
date1.setText("Date Time : "+sdf.format(date));
Java新的日期/时间API
旧的类(Date,Calendar和SimpleDateFormat)具有lots of problems和design issues,它们已被新的API取代.
在Android中,您可以使用ThreeTen Backport,它是Java 8的新日期/时间类的绝佳反向端口.要使其正常工作,您还需要ThreeTenABP(有关如何使用它的更多信息here).
为了从时间戳获取日期,我使用org.threeten.bp.Instant和org.threeten.bp.ZoneId将其转换为时区,从而创建了org.threeten.bp.ZonedDateTime.然后,我使用org.threeten.bp.format.DateTimeFormatter对其进行格式化:
int currentTimeUTCinSeconds = 1504774556;
// get the date in London from the timestamp
ZonedDateTime z = Instant.ofEpochSecond(currentTimeUTCinSeconds).atZone(ZoneId.of("Europe/London"));
// format it
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd yyyy HH:mm:ss 'GMT'XX (zzzz)", Locale.ENGLISH);
System.out.println(fmt.format(z));
输出是相同的:
Thu Sep 07 2017 09:55:56 GMT+0100 (British Summer Time)
就您而言,请执行以下操作:
date1.setText("Date Time : "+fmt.format(z));