如何将UTC时间从数据库转换为设备区域设置

时间:2017-02-09 16:22:32

标签: java android

我正在制作一个聊天应用,并想在新消息输入时存储时间并将此时间存储到数据库中作为字符串我使用此方法

@Override
    public void onClick(View v) {
        if (v == mImageButton) {

            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            timeStamp = simpleDateFormat.format(calendar.getTime());


            MessageModel messageModel = new MessageModel(mUserId,
                    mUserImageUrl,
                    mEditText_message.getText().toString(),
                    mUsername,
                    timeStamp);
            mFirebaseDatabaseRefrence_messages.push().setValue(messageModel);
            mEditText_message.setText(null);
        }
    }

现在我想将此UTC时间转换为设备默认时间,以便我这样做

我也使用这种方法,但这会让我的应用程序崩溃,但这种方法会导致我的应用程序崩溃

String dateStr = model.getTimeStamp();
                SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a");
                df.setTimeZone(TimeZone.getTimeZone("UTC"));
                Date date = null;
                try {
                    date = df.parse(dateStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                df.setTimeZone(TimeZone.getDefault());
                String formattedDate = df.format(date);

                if (model.getTimeStamp() == null) {
                    viewHolder.mTextView_timeStamp.setText("Time");
                } else {
                    viewHolder.mTextView_timeStamp.setText(formattedDate);
                }

1 个答案:

答案 0 :(得分:0)

转换为本地时间使用:

声明Date date;

    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    String timeStamp = simpleDateFormat.format(calendar.getTime());


    try {
        date = simpleDateFormat.parse(timeStamp);
    }catch (Exception e){

    }
    simpleDateFormat.setTimeZone(TimeZone.getDefault());
    String localTime = simpleDateFormat.format(date); //this is the local time