如何根据用户的时区获取用户的时区并转换保存在数据库中的时间?请参阅详细信息

时间:2016-06-24 14:38:11

标签: android datetime date-format simpledateformat android-date

我正在开发一个应用程序,我可以节省发布帖子的时间。

我通过使用此代码获得了这段时间:

DateFormat currentTime = new SimpleDateFormat("h:mm a");
final String time = currentTime.format(Calendar.getInstance().getTime());

现在,我想要的是我想获得用户的时区,并使用他/她的时区将数据库中保存的时间转换为他/她当地时间。

我尝试使用代码执行此操作:

public String convertTime(Date d) {
    //You are getting server date as argument, parse your server response and then pass date to this method

    SimpleDateFormat sdfAmerica = new SimpleDateFormat("h:mm a");

    String actualTime = sdfAmerica.format(d);

    //Changed timezone
    TimeZone tzInAmerica = TimeZone.getDefault();
    sdfAmerica.setTimeZone(tzInAmerica);

    convertedTime = sdfAmerica.format(d);

    Toast.makeText(getBaseContext(), "actual : " + actualTime + "  converted " + convertedTime, Toast.LENGTH_LONG).show();
    return convertedTime;
}

但这并没有改变时间。

这就是我尝试使用上述方法转换保存在数据库中的时间的方法(postedAtTime是从数据库中检索的时间):

String timeStr = postedAtTime;
SimpleDateFormat df = new SimpleDateFormat("h:mm a");
Date date = null;
try {
    date = df.parse(timeStr);
} catch (ParseException e) {
    e.printStackTrace();
}
convertTime(date);

请告诉我代码中的错误或错误方法?

1 个答案:

答案 0 :(得分:1)

您存储的时间字符串不足以在事后更改时区(h:mm a仅为小时,分钟和上午/下午标记)。为了做这样的事情,你需要存储原始时间戳所在的时区,或者更好地以确定的方式存储时间,就像UTC一样。

示例代码:

    final Date now = new Date();
    final String format = "yyyy-MM-dd HH:mm:ss";
    final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
    // Convert to UTC for persistence
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    // Persist string to DB - UTC timezone
    final String persisted = sdf.format(now);
    System.out.println(String.format(Locale.US, "Date is: %s", persisted));

    // Parse string from DB - UTC timezone
    final Date parsed = sdf.parse(persisted);

    // Now convert to whatever timezone for display purposes
    final SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm a Z", Locale.US);
    displayFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));

    final String display = displayFormat.format(parsed);
    System.out.println(String.format(Locale.US, "Date is: %s", display));

输出

Date is: 2016-06-24 17:49:43
Date is: 13:49 PM -0400