Java时间格式化

use*_*rfb 2 java datetime

我有方法

public static void testDateFormat() throws ParseException {
    DateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
    Date hora;
    hora=dateFormat.parse("00:00:01");
    System.out.println(hora.getHours()+" "+hora.getMinutes());
    System.out.println("Date "+hora);
    System.out.println("Seconds "+TimeUnit.MILLISECONDS.toSeconds(hora.getTime()));
}
Run Code Online (Sandbox Code Playgroud)

输出是

0 0
Date Thu Jan 01 00:00:01 COT 1970
Seconds 18001
Run Code Online (Sandbox Code Playgroud)

为什么秒数是18001?我希望得到1秒.

Ell*_*sch 5

因为你Date有一个TimeZone不是UTC.事实上,它是COT--这是UTC-5.5*60*60是18000(或你的结果,再加上一秒).要获得您期望的价值,您可以打电话给DateFormat#setTimeZone(TimeZone),

DateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // <-- Add this.
Date hora=dateFormat.parse("00:00:01");
System.out.println(hora.getHours()+" "+hora.getMinutes());
System.out.println("Date "+hora);
System.out.println("Seconds "+TimeUnit.MILLISECONDS.toSeconds(hora.getTime()));
Run Code Online (Sandbox Code Playgroud)

输出正如您所期望的那样.

编辑 正如评论中所述,Date#getTime()根据Javadoc

返回自此Date对象表示的1970年1月1日00:00:00 GMT以来的毫秒数.

而你Date

Thu Jan 01 00:00:01 COT 1970
Run Code Online (Sandbox Code Playgroud)

相当于

Thu Jan 01 00:05:01 UTC 1970
Run Code Online (Sandbox Code Playgroud)

因此你得到5小时的差异.