samedi 29 août 2015

Android: date formatting method sets time to incorrect time zone

I wrote a date formatting method that is used in a few different views within the app. The problem is that the method returns a time that is four hours behind the time that is inputted by the user.

Here's the relevant part of the method I use to set the original timestamp via the app's Date and TimePicker widgets.

calendar.set(Calendar.MONTH, datePicker.getMonth());
                                calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
                                calendar.set(Calendar.YEAR, datePicker.getYear());

                                calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
                                calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());

                                // Bitmask used to determine timestamp format
                                int displayMask = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
                                String timestamp = DateUtils.formatDateTime(editActivity.getApplicationContext(), calendar.getTimeInMillis(), displayMask);
                                mEditDueDate.setText(timestamp); 

For Example, the would return July 27, 2015, 9:50 PM

This timestamp is then saved in a SQLite database as a datetime string via

public DateTime getTaskDueDate() {
        mDueDate = (EditText) getActivity().findViewById(R.id.task_due_date);
        SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy, h:mm a", Locale.US);
        Date parseDate;
        try {
        parseDate = sdf.parse(mDueDate.getText().toString());
    } catch (ParseException e) {
            Log.getStackTraceString(e);
            return null;
        }
        return new DateTime(parseDate);
    }

The formatting method I use in other parts of the app is,

public String formatDueDate(String queryResponse) {
        DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
        Date date = new Date();
        try {
             date = iso8601Format.parse(queryResponse);
        } catch (ParseException e) {
            Log.e("TAG", "Parsing ISO8601 datetime failed", e);
        }

        long when = date.getTime();
        int flags = 0;
        flags |= android.text.format.DateUtils.FORMAT_SHOW_TIME;
        flags |= android.text.format.DateUtils.FORMAT_SHOW_DATE;
        flags |= android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
        flags |= android.text.format.DateUtils.FORMAT_SHOW_YEAR;

       return android.text.format.DateUtils.formatDateTime(mContext,
                when + TimeZone.getDefault().getOffset(when), flags);

    }

However, this returns July 27 2015, 4:50 PM. Why does formatDueDatereturn a timestamp that is always four hours behind the user inputted timestamp?

Aucun commentaire:

Enregistrer un commentaire