SimpleDateFormat和错误的日期

时间:2014-02-12 20:25:08

标签: java android simpledateformat

我已经尝试了下面的前两个建议,但我再次尝试并真诚地感谢您的帮助!结果虽然如此。我只是编辑帖子以添加更多代码信息。


你好!我正在尝试一个简单的ToDo应用程序,除了用户保存任务后显示的日期格式之外,我设法改变了我想要的几乎所有内容。

任务本身是通过AddToDoActivity类添加的,该类具有以下恢复的代码:

public class AddToDoActivity extends Activity {

// 7 days in milliseconds - 7 * 24 * 60 * 60 * 1000
private static final int SEVEN_DAYS = 604800000;

private static final String TAG = "Lab-UserInterface";

private static String timeString;
private static String dateString;
private static TextView dateView;
private static TextView timeView;


private Date mDate;
private RadioGroup mPriorityRadioGroup;
private RadioGroup mStatusRadioGroup;
private EditText mTitleText;
private RadioButton mDefaultStatusButton;
private RadioButton mDefaultPriorityButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_todo);

    mTitleText = (EditText) findViewById(R.id.title);
    mDefaultStatusButton = (RadioButton) findViewById(R.id.statusNotDone);
    mDefaultPriorityButton = (RadioButton) findViewById(R.id.medPriority);
    mPriorityRadioGroup = (RadioGroup) findViewById(R.id.priorityGroup);
    mStatusRadioGroup = (RadioGroup) findViewById(R.id.statusGroup);
    dateView = (TextView) findViewById(R.id.date);
    timeView = (TextView) findViewById(R.id.time);

    // Set the default date and time

    setDefaultDateTime();

    // OnClickListener for the Date button, calls showDatePickerDialog() to show
    // the Date dialog

    final Button datePickerButton = (Button) findViewById(R.id.date_picker_button);
    datePickerButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            showDatePickerDialog();
        }
    });

    // OnClickListener for the Time button, calls showTimePickerDialog() to show
    // the Time Dialog

    final Button timePickerButton = (Button) findViewById(R.id.time_picker_button);
    timePickerButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            showTimePickerDialog();
        }
    });

    // OnClickListener for the Cancel Button, 

    final Button cancelButton = (Button) findViewById(R.id.cancelButton);
    cancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            log("Entered cancelButton.OnClickListener.onClick()");
            finish();
        }
    });

    //OnClickListener for the Reset Button

    final Button resetButton = (Button) findViewById(R.id.resetButton);
    resetButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            log("Entered resetButton.OnClickListener.onClick()");
            setDefaultDateTime();
            mTitleText.setText("");
            mDefaultStatusButton.setChecked(true);
            mDefaultPriorityButton.setChecked(true);                        

        }
    });

    // OnClickListener for the Submit Button
    // Implement onClick().

    final Button submitButton = (Button) findViewById(R.id.submitButton);
    submitButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            log("Entered submitButton.OnClickListener.onClick()");

            // Gather ToDoItem data  

            Priority priority = getPriority();

            Status status = getStatus();

            String titleString = mTitleText.getText().toString();

            // Date
            String fullDate = dateString + " " + timeString;

            // Package ToDoItem data into an Intent
            Intent data = new Intent();
            ToDoItem.packageIntent(data, titleString, priority, status, fullDate);
            setResult(Activity.RESULT_OK, data);
            finish();

        }
    });
}

// Do not modify below here

    // Use this method to set the default date and time

    private void setDefaultDateTime() {

        // Default is current time + 7 days
        mDate = new Date();
        mDate = new Date(mDate.getTime() + SEVEN_DAYS);

        Calendar c = Calendar.getInstance();
        c.setTime(mDate);

        setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH), 
                c.get(Calendar.YEAR));

        dateView.setText(dateString);

        setTimeString(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
                c.get(Calendar.MILLISECOND));

        timeView.setText(timeString);
    }

    private static void setDateString(int dayOfMonth, int monthOfYear, int year) {

        // Increment monthOfYear for Calendar/Date -> Time Format setting
        monthOfYear++;
        String mon = "" + monthOfYear;
        String day = "" + dayOfMonth;

        if (monthOfYear < 10)
            mon = "0" + monthOfYear;
        if (dayOfMonth < 10)
            day = "0" + dayOfMonth;

        dateString = year + "-" + mon + "-" + day;
    }

    private static void setTimeString(int hourOfDay, int minute, int mili) {
        String hour = "" + hourOfDay;
        String min = "" + minute;

        if (hourOfDay < 10)
            hour = "0" + hourOfDay;
        if (minute < 10)
            min = "0" + minute;

        timeString = hour + ":" + min + ":00";
    }

    private Priority getPriority() {

        switch (mPriorityRadioGroup.getCheckedRadioButtonId()) {
        case R.id.lowPriority: {
            return Priority.LOW;
        }
        case R.id.highPriority: {
            return Priority.HIGH;
        }
        default: {
            return Priority.MED;
        }
        }
    }

    private Status getStatus() {

        switch (mStatusRadioGroup.getCheckedRadioButtonId()) {
        case R.id.statusDone: {
            return Status.DONE;
        }
        default: {
            return Status.NOTDONE;
        }
        }
    }

    // DialogFragment used to pick a ToDoItem deadline date

    public static class DatePickerFragment extends DialogFragment implements
            DatePickerDialog.OnDateSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {

            // Use the current date as the default date in the picker

            final Calendar c = Calendar.getInstance();
            int day = c.get(Calendar.DAY_OF_MONTH);
            int month = c.get(Calendar.MONTH);
            int year = c.get(Calendar.YEAR);


            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        @Override
        public void onDateSet(DatePicker view, int dayOfMonth, int monthOfYear,
                int year) {
            setDateString(dayOfMonth, monthOfYear, year);

            dateView.setText(dateString);
        }

    }

    // DialogFragment used to pick a ToDoItem deadline time

    public static class TimePickerFragment extends DialogFragment implements
            TimePickerDialog.OnTimeSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {

            // Use the current time as the default values for the picker
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return
            return new TimePickerDialog(getActivity(), this, hour, minute,
                    true);
        }

        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            setTimeString(hourOfDay, minute, 0);

            timeView.setText(timeString);
        }
    }

    private void showDatePickerDialog() {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker");
    }

    private void showTimePickerDialog() {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getFragmentManager(), "timePicker");
    }

    private void log(String msg) {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.i(TAG, msg);
    }

}

这是ToDoItem,它实际上从AddToDoActivity读取信息:

public class ToDoItem {

public static final String ITEM_SEP = System.getProperty("line.separator");

public enum Priority {
    LOW, MED, HIGH
};

public enum Status {
    NOTDONE, DONE
};

public final static String TITLE = "title";
public final static String PRIORITY = "priority";
public final static String STATUS = "status";
public final static String DATE = "date";
public final static String FILENAME = "filename";

public final static SimpleDateFormat FORMAT = new SimpleDateFormat(
        "dd/MM/yyyy HH:mm:ss", Locale.US);

private String mTitle = new String();
private Priority mPriority = Priority.LOW;
private Status mStatus = Status.NOTDONE;
private Date mDate = new Date();

ToDoItem(String title, Priority priority, Status status, Date date) {
    this.mTitle = title;
    this.mPriority = priority;
    this.mStatus = status;
    this.mDate = date;
}

// Create a new ToDoItem from data packaged in an Intent

ToDoItem(Intent intent) {

    mTitle = intent.getStringExtra(ToDoItem.TITLE);
    mPriority = Priority.valueOf(intent.getStringExtra(ToDoItem.PRIORITY));
    mStatus = Status.valueOf(intent.getStringExtra(ToDoItem.STATUS));

    try {
        mDate = ToDoItem.FORMAT.parse(intent.getStringExtra(ToDoItem.DATE));
    } catch (ParseException e) {
        mDate = new Date();
    }
}

public String getTitle() {
    return mTitle;
}

public void setTitle(String title) {
    mTitle = title;
}

public Priority getPriority() {
    return mPriority;
}

public void setPriority(Priority priority) {
    mPriority = priority;
}

public Status getStatus() {
    return mStatus;
}

public void setStatus(Status status) {
    mStatus = status;
}

public Date getDate() {
    return mDate;
}

public void setDate(Date date) {
    mDate = date;
}

// Take a set of String data values and 
// package them for transport in an Intent

public static void packageIntent(Intent intent, String title,
        Priority priority, Status status, String date) {

    intent.putExtra(ToDoItem.TITLE, title);
    intent.putExtra(ToDoItem.PRIORITY, priority.toString());
    intent.putExtra(ToDoItem.STATUS, status.toString());
    intent.putExtra(ToDoItem.DATE, date);

}

public String toString() {
    return mTitle + ITEM_SEP + mPriority + ITEM_SEP + mStatus + ITEM_SEP
            + FORMAT.format(mDate);
}

public String toLog() {
    return "Title:" + mTitle + ITEM_SEP + "Priority:" + mPriority
            + ITEM_SEP + "Status:" + mStatus + ITEM_SEP + "Date:"
            + FORMAT.format(mDate);
}

}

哦,好几个小时后调整了“public final static SimpleDateFormat FORMAT = new SimpleDateFormat(”yyyy-MM-dd HH:mm:ss“,Locale.US);”来自ToDoItem的方法,我仍然无法成功将yyyy-MM-dd转换为dd / MM / yyyy。

首先,我尝试了显而易见的,并将表达式yyyy-MM-dd更改为dd / MM / yyyy。
之后,即使在AddToDoActivity上输入的日期提前数月或数年,我保存任务后的所有内容都是今天的日期。 如果我恢复到yyyy-MM-dd,任务列表上显示的日期与AddToDoActivity上输入的日期相同。

然后我试图改变每个班级的所有日期提及,以匹配我想要的确切格式 这使得AddToDoActivity上的一切看起来都很好,但是当我将日期传回ToDoItem时,应用程序只是忽略了之前输入的日期并再次显示今日日期。

任何人都可以帮我解决这个问题吗?

谢谢!

3 个答案:

答案 0 :(得分:0)

您使用年,月,日的顺序调用setDateString

setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
        c.get(Calendar.DAY_OF_MONTH));

但是你的方法的参数按日,月,年的顺序排列:

private static void setDateString(int dayOfMonth, int monthOfYear, int year) {
    ...
}

我还认为您在将代码复制到问题时遇到了一些错误,因为setDateString方法是重复的,并且没有setTimeString方法。

答案 1 :(得分:0)

变化:

 setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));

为:

setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH), c.get(Calendar.YEAR));

答案 2 :(得分:0)

ToDoListAdapter 文件getView方法中进行如下修改

    // TODO - Display Time and Date. 
    // Hint - use ToDoItem.FORMAT.format(toDoItem.getDate()) to get date and time String

    final TextView dateView = (TextView) itemLayout.findViewById(R.id.dateView);
    dateView.setText(ToDoItem.FORMAT.format(toDoItem.getDate()));

输出将类似于以下内容

UILabs Output

参考