如何获取用户的时区并根据用户的时区转换数据库中保存的时间?请查看详情

How to get user's timezone and convert time saved in database according to the user's timezone? Please see details

我正在开发一个应用程序,在 post posted 时,我可以在其中节省时间。

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

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

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

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

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);

请告诉我我的代码有什么问题,或者这是错误的方法吗?

您存储的时间字符串不足以在事后更改时区(h:mm a 只是小时、分钟和 am/pm 标记)。为了做这样的事情,您需要存储原始时间戳所在的时区,或者更好地以确定性方式存储时间,如始终使用 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