Java将UTC时间戳转换为本地DateTime

kaz*_*uya 4 java datetime android timestamp

我知道有很多关于将UTC时间/日期转换为当地时间的回复帖子,但没有帮助我弄清楚我的问题是什么.我的问题是:通过UTC时间戳,我怎样才能获得本地DateTime?这就是我现在所拥有的,但这只是将时间戳转换为DateTime格式.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getDefault());         
sdf.format(new Date(timestamp * 1000));
Run Code Online (Sandbox Code Playgroud)

编辑:我在云上保存UTC时间戳,以便每个设备(Android/iOS)都可以查询并转换为它的时区.

Bir*_*dia 16

试试这个和我一起工作

public  String getDateCurrentTimeZone(long timestamp) {
        try{
            Calendar calendar = Calendar.getInstance();
            TimeZone tz = TimeZone.getDefault();
            calendar.setTimeInMillis(timestamp * 1000);
            calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date currenTimeZone = (Date) calendar.getTime();
            return sdf.format(currenTimeZone);
        }catch (Exception e) {
        }
        return "";
    }
Run Code Online (Sandbox Code Playgroud)