【问题标题】:Android: Date is not being displayed as local timeAndroid:日期未显示为当地时间
【发布时间】:2016-02-25 09:49:50
【问题描述】:

我正在尝试从sqlite 数据库中检索date 并将其显示在文本视图中。尽管使用了 TimeZone.getDefault(),时间仍然显示为 GMT 时间,而不是本地时间。

这是我尝试将日期转换为本地时间的方法:

public String formatDate(String stringDate) {
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
    try {
        Date date = sdf.parse(stringDate);
        TimeZone tz = TimeZone.getDefault();
        sdf.setTimeZone(tz);
        Log.v("formatDate", "TimeZone   " + tz.getDisplayName(false, TimeZone.SHORT) + " Timezon id :: " + tz.getID());
        return sdf.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return stringDate;
}

如您所见,我想查看时区 是否 实际上是本地时间,并为此添加了一条日志语句。这是日志语句的输出:

02-25 15:15:55.422 29855-29855/com.example.ishita.assigntasks V/formatDate: TimeZone   GMT+05:30 Timezon id :: Asia/Calcutta

这是我打电话给formatDate()的那一行:

viewHolder.timeStamp.setText(formatDate(cursor.getString(cursor.getColumnIndex(TasksContract.MessageEntry.COL_AT))));

请指出我哪里出错了,以及我可以做些什么来在设备使用的时区显示日期/时间。

【问题讨论】:

  • 你能添加示例输入和输出吗?

标签: android sqlite datetime


【解决方案1】:

我认为您没有转换任何内容,因为SimpleDateFormat 默认使用默认时区,因此您正在解析和格式化具有相同时区的日期。如果您在解析日期之前将时区设置为 UTC(然后在格式化之前恢复为默认值)会发生什么? :

    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");

    // convert from UTC
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    try {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2021-01-18
    相关资源
    最近更新 更多