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

2022-01-13 00:00:00 datetime timestamp android java

我知道已经有几十篇关于将 UTC 时间/日期转换为/从本地时间的回复帖子,但没有帮助我弄清楚我的问题是什么.我的问题是:通过拥有 UTC 时间戳,我如何获得本地 DateTime?这就是我现在所拥有的,但这只是将时间戳转换为 DateTime 格式.

I know there are dozens of answered posts about converting UTC Time/Date To/From local time already but non helped me to figure out what my problem is. My question is: By having UTC timestamp, how can i get local DateTime? This is what I have right now but this just convert the timestamp to DateTime format.

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

已我将 UTC 时间戳保存在云端,以便每台设备(Android/iOS)都可以查询并转换到它的时区.

Edited: I'm saving the UTC timestamp on the cloud so every device (Android/iOS) can query and convert to it's time zone.

推荐答案

试试这个对我有用

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 "";
    }

相关文章