Comparing two times in android

前端 未结 4 887
梦如初夏
梦如初夏 2021-01-02 23:57

I have tried with the below code to compare two times:

   SimpleDateFormat sdf = new SimpleDateFormat(\"hh:mm\");
    Date inTime = sdf.parse(\"11:00\");
            


        
相关标签:
4条回答
  • 2021-01-03 00:29
    import android.app.Dialog;
    import android.app.TimePickerDialog;
    import android.content.Context;
    import android.os.Bundle;
    import android.support.v4.app.DialogFragment;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.TimePicker;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    
    /**
     * Created by Ketan Ramani on 20/9/18.
     */
    
    public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
        private static EditText text;
        private static TextView textTv;
        private static Date startDate = null;
        private static Date fromTime = null;
    
        public static TimePickerFragment getInstance(View view) {
            if (view instanceof EditText) {
                text = (EditText) view;
            } else if (view instanceof TextView) {
                textTv = (TextView) view;
            }
    
            return new TimePickerFragment();
        }
    
        public static TimePickerFragment getInstance(View view, Date fromTimeCalendar) {
            if (view instanceof EditText) {
                text = (EditText) view;
            } else if (view instanceof TextView) {
                textTv = (TextView) view;
            }
    
            fromTime = fromTimeCalendar;
    
            return new TimePickerFragment();
        }
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            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 it
            return new TimePickerDialog(getActivity(), this, hour, minute, true/*DateFormat.is24HourFormat(getActivity())*/);
        }
    
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    
            if (fromTime != null) {
    
                Calendar fromTimeCal = Calendar.getInstance();
                fromTimeCal.setTime(fromTime);
    
                SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
                Date toDate = null;
                try {
                    toDate = sdf.parse(String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
    
                Calendar toTimeCal = Calendar.getInstance();
                toTimeCal.setTime(toDate);
    
                if (toTimeCal.getTimeInMillis()<fromTimeCal.getTimeInMillis()){
                    Helper.showToast(getActivity(),"To time can't less than from time");
                } else {
                    if (text != null) {
                        text.setText(getFormatedTime(hourOfDay, minute));
                    } else if (textTv != null) {
                        textTv.setText(getFormatedTime(hourOfDay, minute));
                    }
                }
            } else {
                if (text != null) {
                    text.setText(getFormatedTime(hourOfDay, minute));
                } else if (textTv != null) {
                    textTv.setText(getFormatedTime(hourOfDay, minute));
                }
            }
        }
    
        private String getFormatedTime(int hourOfDay, int minute) {
            int hour, min;
            Calendar datetime = Calendar.getInstance();
            String am_pm = "";
            datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
            datetime.set(Calendar.MINUTE, minute);
    
            if (datetime.get(Calendar.AM_PM) == Calendar.AM)
                am_pm = "AM";
            else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
                am_pm = "PM";
            hourOfDay = hourOfDay > 12 ? hourOfDay - 12 : hourOfDay;
            hour = hourOfDay > 9 ? hourOfDay : hourOfDay;
            min = minute > 9 ? minute : minute;
    
            return String.format("%02d", hour) + ":" + String.format("%02d", min) + " " + am_pm;
        }
    
        public void showTimePickerDialog(Context context, View view) {
            DialogFragment newFragment = TimePickerFragment.getInstance(view);
            newFragment.show(((AppCompatActivity) context).getSupportFragmentManager(), "TimePicker");
        }
    
        public void showTimePickerDialog(Context context, View view, Date fromTime) {
            DialogFragment newFragment = TimePickerFragment.getInstance(view, fromTime);
            newFragment.show(((AppCompatActivity) context).getSupportFragmentManager(), "TimePicker");
        }
    }
    

    Use

    @Override
        public void onClick(View v) {
            switch (v.getId()) {
    
                case R.id.et_from_time:
    
                    TimePickerFragment fromTime = new TimePickerFragment();
                    fromTime.showTimePickerDialog(context, v, null);
    
                    mToTimeEt.setText("Select To Time");
                    break;
    
                case R.id.et_to_time:
    
                    if(mFromTimeEt.getText().toString().equalsIgnoreCase("Select From Time")){
                        Helper.showToast(context,"Please, select from time first");
                    } else {
                        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
                        Date fromDate = null;
                        try {
                            fromDate = sdf.parse(mFromTimeEt.getText().toString());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
    
                        TimePickerFragment toTime = new TimePickerFragment();
                        toTime.showTimePickerDialog(context, v, fromDate);
                    }
                    break;
            }
        }
    

    This class will work for EditText and TextView and set time to respected EditText or TextView if To time is After From Time in HH:mm a Format

    0 讨论(0)
  • 2021-01-03 00:37

    tl;dr

    Use java.time.

    LocalTime
    .parse( "12:00" )
    .isAfter(
        LocalTime.parse( "11:00" ) 
    )
    

    java.time

    You have three problems:

    • You are using terrible old date-time classes (Date & SimpleDateFormat) that were supplanted years ago by the modern java.time classes.
    • Your format of hh:mm should have been uppercase for 24-hour clock rather than 12-hour clock: HH:mm.
    • You are inappropriately trying to represent a time-of-day with a class meant for date-with-time-of-day values.

    Use LocalTime. This class represents a time-of-day without a date and without a time zone.

    LocalTime start = LocalTime.parse( "11:00" ) ;
    LocalTime stop = LocalTime.parse( "12:00" ) ;
    

    You can compare.

    boolean isStopAfterStart = stop.isAfter( start ) ;
    

    Calculate the elapsed time as a Duration.

    Duration d = Duration.between( start , stop ) ;
    

    d.toString(): PT1H

    You can also ask the Duration if it is negative, as another way to detect the stop time being before the start.

    boolean isStopBeforeStart = d.isNegative() ;
    

    Caveat: Working on time-of-day without the context of a date and a time zone can produce unrealistic results. That approach ignores the anomalies that occur in time zones such as Daylight Saving Time (DST) and other shifts to the wall-clock time used by the people of a particular region. An hour can repeat, or be skipped. A day can be 23, 23.5, 23.75, 25, or other number of hours long.


    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

    Where to obtain the java.time classes?

    • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • Later versions of Android bundle implementations of the java.time classes.
      • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
    0 讨论(0)
  • 2021-01-03 00:38

    If you are using 24 hour time format then use kk instead of HH.

     SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
    
    0 讨论(0)
  • 2021-01-03 00:52

    Change SimpleDateFormat like below...

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    

    Below are the patterns:

    H   Hour in day (0-23)  Number  0
    k   Hour in day (1-24)  Number  24
    K   Hour in am/pm (0-11)    Number  0
    h   Hour in am/pm (1-12)    Number  12
    

    This will work....

    0 讨论(0)
提交回复
热议问题