小编xun*_*nts的帖子

即使您选择任何时区,以秒为单位的时间也是相同的?

在应用 TimeZone“Europe/Warsaw”后,我使用以下函数以秒为单位获取时间。

我正确获取日期,但是一旦我以秒为单位转换日期,我的输出就会出错。服务器期望时区“欧洲/华沙”中的秒数。摆脱这种困境的最佳方法是什么?

public static long getTimeInSeconds() {
    try {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //Here you say to java the initial timezone. This is the secret
        sdf.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));

        //Will get in Warsaw time zone
        String date = sdf.format(calendar.getTime());

        Date date1 = sdf.parse(date);

        //Convert time in seconds as required by server.
        return (date1.getTime() / 1000);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

java timezone datetime epoch

1
推荐指数
1
解决办法
780
查看次数

标签 统计

datetime ×1

epoch ×1

java ×1

timezone ×1