在android中比较两次

时间:2013-12-02 05:52:50

标签: android time toast

我尝试使用以下代码进行两次比较:

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

    if(inTime.compareTo(outTime) > 0){
    Toast.makeText(this, "Out time should be greater than In time", Toast.LENGTH_SHORT).show();
    }

以上代码工作正常。

但是,如果我及时将时间作为11:00和时间作为12:00,我就会收到上面的祝词。

如果我在12:00到12:59之间给出时间,我会收到toast留言。在其他情况下,上面的代码工作正常。

我做错了。请帮帮我。

4 个答案:

答案 0 :(得分:5)

更改SimpleDateFormat,如下所示......

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

以下是模式:

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

这将有效....

答案 1 :(得分:0)

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");
    }
}

使用

@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;
        }
    }

如果“时间”为HH:mm格式,则该类将适用于EditText和TextView并将时间设置为受尊重的EditText或TextView

答案 2 :(得分:0)

tl; dr

使用 java.time

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

java.time

您遇到三个问题:

  • 您使用的是可怕的旧日期时间类(DateSimpleDateFormat),而这些类早在几年前就被现代的 java.time 类所取代。
  • 您的hh:mm格式应该为24小时大写,而不是12小时:HH:mm
  • 您不恰当地尝试使用旨在表示日期和日期的值的类来表示日期。

使用LocalTime。此类表示一天中没有日期和时区的时间。

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

您可以比较。

boolean isStopAfterStart = stop.isAfter( start ) ;

将经过时间计算为Duration

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

d.toString():PT1H

您也可以ask the Duration if it is negative,作为检测停止时间在开始之前的另一种方法。

boolean isStopBeforeStart = d.isNegative() ;

注意事项:在没有日期和时区上下文的情况下进行工作可能会产生不切实际的结果。该方法忽略了在时区中发生的异常,例如夏令时(DST)以及特定地区人们使用的挂钟时间的其他转变。一个小时可以重复,也可以跳过。一天可以是23、23.5、23.75、25或其他小时数。


关于 java.time

java.time框架已内置在Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendarSimpleDateFormat

目前位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解更多信息,请参见Oracle Tutorial。并在Stack Overflow中搜索许多示例和说明。规格为JSR 310

您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*类。

在哪里获取java.time类?

答案 3 :(得分:-1)

如果您使用24小时时间格式,请使用kk代替HH

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