DateFormat和TimeFormat(StartDate - EndDate)

时间:2014-03-09 12:52:21

标签: android date-format time-format

请帮助解决两个问题:

在代码和我的什么时候将日期格式和时间格式更改为24小时?我没有成功。

如何计算开始日期和结束日期之间的差异(例如:最近2天和5小时)?

    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import ru.zloyel.manager_sutochnoy_arendy_1.DatePickerFragmentS.DatePickedListenerS;
    import ru.zloyel.manager_sutochnoy_arendy_1.DatePickerFragmentE.DatePickedListenerE;
    import ru.zloyel.manager_sutochnoy_arendy_1.TimePickerFragmentS.TimePickerListenerS;
    import ru.zloyel.manager_sutochnoy_arendy_1.TimePickerFragmentE.TimePickerListenerE;
    import android.app.Activity;
    import android.app.DialogFragment;
    import android.content.Intent;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.RadioButton;
    import android.widget.Spinner;

    public class Zaselenie extends Activity implements DatePickedListenerS, DatePickedListenerE,
            TimePickerListenerS, TimePickerListenerE {

        ContactDBmoy cqh;
        KvartDB kdb;
        SQLiteDatabase sdb;
        SQLiteDatabase sdb2;

        private Long rowId;

        Spinner spKvart, spContact;
        RadioButton rbZaselenie, rbBron;

        EditText etDateStart;
        EditText etTimeStart;
        EditText etDateEnd;
        EditText etTimeEnd;

        ImageView icDateStart;
        ImageView icTimeStart;
        ImageView icDateEnd;
        ImageView icTimeEnd;

        ImageView icKvartAdd;
        ImageView icContAdd;

        Button btnSaveZas;

        private int mYear;
        private int mMonth;
        private int mDay;
        private int mHour;
        private int mMinute;

        private Calendar c;

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

            spKvart = (Spinner) findViewById(R.id.spKvart);
            spContact = (Spinner) findViewById(R.id.spContact);

            rbZaselenie = (RadioButton) findViewById(R.id.rbZaselenie);
            rbBron = (RadioButton) findViewById(R.id.rbBron);

            etDateStart = (EditText) findViewById(R.id.etDateStart);
            etTimeStart = (EditText) findViewById(R.id.etTimeStart);
            etDateEnd = (EditText) findViewById(R.id.etDateEnd);
            etTimeEnd = (EditText) findViewById(R.id.etTimeEnd);

            icContAdd = (ImageView) findViewById(R.id.icContAdd);
            icKvartAdd = (ImageView) findViewById(R.id.icKvartAdd);

            icDateStart = (ImageView) findViewById(R.id.icDateStart);
            icDateEnd = (ImageView) findViewById(R.id.icDateEnd);
            icTimeStart = (ImageView) findViewById(R.id.icTimeStart);
            icTimeEnd = (ImageView) findViewById(R.id.icTimeEnd);

            btnSaveZas = (Button) findViewById(R.id.btnSaveZas);

            // Инициализируем наш класс-обёртку
            cqh = new ContactDBmoy(Zaselenie.this);
            kdb = new KvartDB(Zaselenie.this);

            // База нам нужна для записи и чтения
            sdb2 = cqh.getWritableDatabase();
            sdb = kdb.getWritableDatabase();

            // получаем текущее время
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH) + 1;
            mDay = c.get(Calendar.DAY_OF_MONTH);
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);

            // выводим текущее время
            updateDisplayStart();
            updateDisplayEnd();

            Bundle extras = getIntent().getExtras();

            if (extras != null) {
                rowId = extras.getLong(KvartityMain.rowId);
            }

            if (extras != null) {
                rowId = extras.getLong(ContactMain.rowId);
            }




            // * Помещаем список квартир в спиннер

            Cursor cursorKvart = sdb.query(KvartDB.TABLE_NAME, new String[] {
                    KvartDB._ID, KvartDB.NAME_COLUMN }, null, null,
                    KvartDB.NAME_COLUMN, null, null);

            ArrayList<String> labelsKvart = new ArrayList<String>();
            while (cursorKvart.moveToNext()) {
                // GET COLUMN INDICES + VALUES OF THOSE COLUMNS
                int idKvart = cursorKvart.getInt(cursorKvart
                        .getColumnIndex(KvartDB._ID));
                String nameKvart = cursorKvart.getString(cursorKvart
                        .getColumnIndex(KvartDB.NAME_COLUMN));
                Log.i("LOG_TAG", "ROW " + idKvart + " HAS NAME " + nameKvart);

                labelsKvart.add(nameKvart);
                // Creating adapter for spinner
                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_spinner_item, labelsKvart);

                // Drop down layout style - list view with radio button
                dataAdapter
                        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter.notifyDataSetChanged();

                // attaching data adapter to spinner
                spKvart.setAdapter(dataAdapter);
            }

            cursorKvart.close();


            // * Помещаем список контактов в спиннер


            Cursor cursorContact = sdb2.query(ContactDBmoy.TABLE_NAME,
                    new String[] { ContactDBmoy._ID, ContactDBmoy.COLUMN_NAME },
                    null, null, ContactDBmoy.COLUMN_NAME, null, null);

            ArrayList<String> labelsContact = new ArrayList<String>();

            while (cursorContact.moveToNext()) {
                // GET COLUMN INDICES + VALUES OF THOSE COLUMNS
                int idContact = cursorContact.getInt(cursorContact
                        .getColumnIndex(ContactDBmoy._ID));
                String nameContact = cursorContact.getString(cursorContact
                        .getColumnIndex(ContactDBmoy.COLUMN_NAME));
                Log.i("LOG_TAG", "ROW " + idContact + " HAS NAME " + nameContact);

                labelsContact.add(nameContact);
                // Creating adapter for spinner
                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_spinner_item, labelsContact);

                // Drop down layout style - list view with radio button
                dataAdapter
                        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter.notifyDataSetChanged();

                // attaching data adapter to spinner
                spContact.setAdapter(dataAdapter);
            }
            cursorContact.close();

        }

        public Zaselenie() {
            // TODO Auto-generated constructor stub
        }

        @Override
        protected void onResume() {
            super.onResume();

        }

        @Override
        protected void onStop() {
            super.onStop();
            // закрываем соединения с базой данных
            sdb.close();
            sdb2.close();
            cqh.close();
            kdb.close();
        }



        // * Методы для кнопок рядом со спиннерами

        public void onClickKvartAdd(View v) {

            Intent kvartAdd = new Intent(this, Kvartiry.class);
            startActivity(kvartAdd);
        }

        public void onClickContAdd(View v) {

            Intent contAdd = new Intent(this, Contact.class);
            startActivity(contAdd);
        }



        // * Методы для вызова диалогов даты и времени

        public void onClickDateStart(View v) {
            DialogFragment dateFragment = new DatePickerFragmentS();
            dateFragment.show(getFragmentManager(), "datePicker");
        }

        public void onClickDateEnd(View v) {
            DialogFragment dateFragment = new DatePickerFragmentE();
            dateFragment.show(getFragmentManager(), "datePicker");
        }

        public void onClickTimeStart(View view) {
            DialogFragment timeFragment = new TimePickerFragmentS();
            timeFragment.show(getFragmentManager(), "timePicker");
        }

        public void onClickTimeEnd(View view) {
            DialogFragment timeFragment = new TimePickerFragmentE();
            timeFragment.show(getFragmentManager(), "timePicker");
        }




         // Convenience wrapper for internal Calendar instance
        public long getDateTimeMillis() {
            return c.getTimeInMillis();
        }



        public void onDatePickedS(Calendar date) {
            // выводим выбранную дату в текстовой метке 461
            mYear = date.get(Calendar.YEAR);
            mMonth = date.get(Calendar.MONTH) + 1;
            mDay = date.get(Calendar.DAY_OF_MONTH);

            updateDisplayStart();
        }

        public void onDatePickedE(Calendar date) {
            // выводим выбранную дату в текстовой метке 461
            mYear = date.get(Calendar.YEAR);
            mMonth = date.get(Calendar.MONTH) + 1;
            mDay = date.get(Calendar.DAY_OF_MONTH);

            updateDisplayEnd();
        }

        public void onTimePickerS(Calendar time) {
            // выводим выбранную дату в текстовой метке 461
            mHour = time.get(Calendar.HOUR);
            mMinute = time.get(Calendar.MINUTE);

            updateDisplayStart();
        }

        public void onTimePickerE(Calendar time) {
            mHour = time.get(Calendar.HOUR);
            mMinute = time.get(Calendar.MINUTE);

            updateDisplayEnd();
        }

        // обновляем дату для вывода в TextView
        public void updateDisplayStart() {


            etDateStart.setText(new StringBuilder().append(mDay).append(".")
                    .append(mMonth).append(".").append(mYear));




            etTimeStart.setText(new StringBuilder().append(mHour).append(":")
                    .append(mMinute));

        }

        public void updateDisplayEnd() {


            etDateEnd.setText(new StringBuilder().append(mDay).append(".")
                    .append(mMonth).append(".").append(mYear));




            etTimeEnd.setText(new StringBuilder().append(mHour).append(":")
                    .append(mMinute));
        }

    }

1 个答案:

答案 0 :(得分:1)

Android TimePicker Set 24 Hours

TimePicker是用于选择 24小时 AM / PM 模式的时间的视图。 您可以将setIs24HourView(true)方法与TimePicker.

一起使用

Android代码

timePicker = (TimePicker) findViewById(R.id.timePicker1);
timePicker.setIs24HourView(true);
timePicker.setCurrentHour(Calendar.get(Calendar.HOUR_OF_DAY));

开始日期和结束日期之间的区别使用jodatime API

Days.daysBetween(start.toDateMidnight() , end.toDateMidnight() ).getDays() 

其中'start'和'end'是您的DateTime个对象。要将日期字符串解析为DateTime对象,请使用parseDateTime method

如果您不使用jodatimeAPI,请按照以下方式执行操作,

Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);

Calendar today = Calendar.getInstance();

long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000); // approximation

如果从字符串解析日期。你可以用

String strThatDay = "1990/06/20";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
  d = formatter.parse(strThatDay);
} catch (ParseException e) {
  System.err.println("Error: " + e.getMessage());
} 

Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....