【问题标题】:Convert Received date time to local timezone time Android将收到的日期时间转换为本地时区时间 Android
【发布时间】:2016-07-22 20:16:52
【问题描述】:

美好的一天。我正在构建一个聊天应用程序。出于目的,我决定设置消息发送的日期。毫无疑问,在不同国家/地区的日期必须显示不同。例如,让我们以 2 个不同的国家/地区为例并假设不同它们之间是 2 小时。CountryX 和 CountryY。用户从 CountryX 发送消息,时间可以说是 15:00。我将其保存在服务器上,与用户发送的确切时区时间相同,确切地说是 15:00,因为 CountryX.Second 用户收到CountryY 中的消息,距离 CountryX 2 小时多,所以基本上我必须在 CountryY 显示的时间必须是 17:00。这是问题所在。如何将已知时区的已接收时间转换为本地时间以便显示对吗?我用谷歌搜索了很多,但我想出了一些解决方案,您只需获取确切国家/地区的时间,而不是将 CountryX 发送的时间转换为 CountryY 当地时间以在 CountryY 中正确显示它。请您提供一个帮助?非常感谢您。

【问题讨论】:

  • 查看名为:PrettyTime 的库,适合聊天和本地时区
  • 好的,现在看看它会提供什么
  • 好像找不到需要的方法
  • 对于这种情况,您只需要 UTC。

标签: android time timezone


【解决方案1】:

对于因此而受苦的每个人。我最终用我自己的逻辑创建了自己的类,它完美地工作,并且随着时间的推移作为额外的奖励几个方便的方法

public class Time {
    public static String getCurrentTime() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        String finalFormat = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
        if (month < 10) {
            String finalMonth = "0" + month;
            finalFormat = year + "-" + finalMonth + "-" + day + " " + hour + ":" + minute + ":" + second;
        }

        return finalFormat;
    }

    public static String convertToLocalTime(String timeToConvert) {
        SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sourceFormat.setTimeZone(TimeZone.getTimeZone(Constants.SERVER_TIME_ZONE));//where server time zone is the time zone of your server as defauul,E.X -America/Los_Angeles
        Date parsed;
        try {
            parsed = sourceFormat.parse(timeToConvert);
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }

        TimeZone tz = TimeZone.getDefault();
        SimpleDateFormat destFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        destFormat.setTimeZone(tz);

        String result = destFormat.format(parsed);
        return result;
    }

    public static String getTimeZone() {
        return TimeZone.getDefault().getID();
    }
}

【讨论】:

    猜你喜欢
    • 2021-05-02
    • 2019-01-14
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 2018-08-21
    • 2016-09-12
    相关资源
    最近更新 更多