trigster
trigster

Reputation: 97

Set date and time into an local variable - Android

I have created a form where the user can pick the date and time:

@Override
public void onClick(View v) {
    //Get the date
    if(v == buttonDatePicker){

        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        etDate.setText(dayOfMonth + "-" + month + "-" + year);
                    }
                },mYear,mMonth,mDay);
        datePickerDialog.show();

    }
    //Get the time
    if(v == buttonTimePicker){

        mHour = calendar.get(Calendar.HOUR_OF_DAY);
        mMinute = calendar.get(Calendar.MINUTE);

        TimePickerDialog timePickerDialog = new TimePickerDialog(this,
                new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                etTime.setText(hourOfDay + ":" + minute);
            }
        },mHour,mMinute,true);
        timePickerDialog.show();
    }
}

This works fine, but how would you then store the date and time into their own variables, so that I can then store those var into my SQLite database? I thought creating a date and time object and then setting the from there would do the trick, but when I use date, the get methods are now depreciated.

Do I need to convert the date and time to long vars, like so:

Long pHour = (long) mHour; and the same for minute, then join them together and then set it via setTime? but then how do I join them together?

Thanks If anyone has any doc/tut on doing this that would also be good.

Upvotes: 1

Views: 1180

Answers (2)

user8959091
user8959091

Reputation:

As Radesh proposed you can store dates using calendar.getTimeInMillis() which includes date and time, but I prefer to store date/time together as string in this format: "yyyy-MM-dd hh:mm:ss".

Upvotes: 0

Radesh
Radesh

Reputation: 13565

store in TimeInMillis

long storeVal = calendar.getTimeInMillis();

then save storeVal into sharedPreferenses or SQl database

Upvotes: 2

Related Questions