如何比较当前时间与时间范围?

时间:2011-06-16 19:13:45

标签: java time

我有两个字符串变量 - time1time2。两者都包含 HH:MM 格式的值。我该如何检查:

  1. 如果当前时间在 time1time2?
  2. time1将在最近的地方发生 小时?
  3. UPD。 我已实施以下内容将time1转换为Date格式。但它使用折旧方法:

    Date clTime1 = new Date();
    
    SimpleDateFormat timeParser = new SimpleDateFormat("HH:mm", Locale.US);
    try {
      clTime1 = timeParser.parse(time1);
    } catch (ParseException e) {
    }
    
    Calendar now = Calendar.getInstance();
    clTime1.setYear(now.get(Calendar.YEAR) - 1900);
    clTime1.setMonth(now.get(Calendar.MONTH));
    clTime1.setDate(now.get(Calendar.DAY_OF_MONTH));
    System.out.println(clTime1.toString());
    

9 个答案:

答案 0 :(得分:22)

  • 将两个字符串转换为Date 对象(也是时间对象) 创建一个新的Date对象。
  • 这会 包含当前时间。
  • 使用 Date.before()和Date.after()方法确定是否 你在时间间隔内。

编辑:你应该能够直接使用它(并且没有弃用的方法)

public static final String inputFormat = "HH:mm";

private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;

private String compareStringOne = "9:45";
private String compareStringTwo = "1:45";

SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);

private void compareDates(){
    Calendar now = Calendar.getInstance();

    int hour = now.get(Calendar.HOUR);
    int minute = now.get(Calendar.MINUTE);

    date = parseDate(hour + ":" + minute);
    dateCompareOne = parseDate(compareStringOne);
    dateCompareTwo = parseDate(compareStringTwo);

    if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
        //yada yada
    }
}

private Date parseDate(String date) {

    try {
        return inputParser.parse(date);
    } catch (java.text.ParseException e) {
        return new Date(0);
    }
}

答案 1 :(得分:4)

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

Date EndTime = dateFormat.parse("10:00");

Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));

if (CurrentTime.after(EndTime))
{
    System.out.println("timeeee end ");
}

不要忘记用try catch块包围

答案 2 :(得分:3)

这是我用过的,它对我有用:

public static boolean isTimeWith_in_Interval(String valueToCheck, String endTime, String startTime) {
    boolean isBetween = false;
    try {
        Date time1 = new SimpleDateFormat("HH:mm:ss").parse(endTime);

        Date time2 = new SimpleDateFormat("HH:mm:ss").parse(startTime);

        Date d = new SimpleDateFormat("HH:mm:ss").parse(valueToCheck);

        if (time1.after(d) && time2.before(d)) {
            isBetween = true;
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return isBetween;
}

答案 3 :(得分:1)

查看Calendar类。它有支持你所要求的方法。不推荐使用日期,不建议使用。

以下是API的链接。 Calendar

关于用法。首先,您需要调用Calendar.getInstance()来创建日历对象。 接下来,您需要以相同的方式使用cal.set(Calendar.HOUR, your hours)Calendar.MINUTES设置两个字段。接下来,您可以在函数之前或之后调用compare函数来获取所需的信息。您还可以使用当前语言环境中的当前时间获取实例。

答案 4 :(得分:1)

例如,如果您想比较晚上11点到早上6点之间的时间来计算任何车辆的额外夜间票价。然后下面的代码将帮助你。

//代码

package com.example.timedate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import android.os.Bundle;
import android.app.Activity;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    TextView tv;
    Button bt;
    int hour,min;
    String AM_PM;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.textView1);
        bt = (Button)findViewById(R.id.button1);



        final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());*/

        bt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub


                Calendar c = Calendar.getInstance();
                hour = c.get(Calendar.HOUR_OF_DAY);
                min = c.get(Calendar.MINUTE);
                int ds = c.get(Calendar.AM_PM);
                if(ds==0)
                AM_PM="am";
                else
                AM_PM="pm";

                Toast.makeText(MainActivity.this, ""+hour+":"+min+AM_PM, Toast.LENGTH_SHORT).show();
                if((hour==11&&AM_PM.matches("pm")) || (hour<7&&AM_PM.matches("am"))  || (hour==12&&AM_PM.matches("am")))
                {
                    Toast.makeText(MainActivity.this, "Time is between the range", Toast.LENGTH_SHORT).show();
                }
                else
                    Toast.makeText(MainActivity.this, "Time is not between the range", Toast.LENGTH_SHORT).show();

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}`

答案 5 :(得分:0)

截至目前,我正在考虑以下方法:

int clTime = Integer.parseInt(time1.substring(0, 1))*60 + Integer.parseInt(time1.substring(3, 4)); 

Time now = new Time();
now.setToNow();
int nowTime = now.hour*60 + now.minute;

所以,我需要只比较整数值clTimenowTime

答案 6 :(得分:0)

    Try this if you have specific time Zone.  

              try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("hh a");
            Date timeseven = dateFormat.parse("7 AM");
            Date timeTen = dateFormat.parse("10 AM");
            Date timeOne = dateFormat.parse("1 PM");
            Date timefour = dateFormat.parse("4 PM");
            Date timefive = dateFormat.parse("10 PM");
            //Get current time
            // Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
            //Sample time 
            Date CurrentTime = dateFormat.parse("9 PM");

            if (CurrentTime.after(timeseven) && CurrentTime.before(timeTen)) {
                Toast.makeText(this, "FIRST", Toast.LENGTH_SHORT).show();
            } else if (CurrentTime.after(timeTen) && CurrentTime.before(timeOne)) {
                Toast.makeText(this, "Secound", Toast.LENGTH_SHORT).show();
            } else if (CurrentTime.after(timeOne) && CurrentTime.before(timefour)) {
                Toast.makeText(this, "THird", Toast.LENGTH_SHORT).show();
            } else if (CurrentTime.after(timefour) && CurrentTime.before(timefive)) {
                Toast.makeText(this, "Fourth", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Not found in your time zone", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

答案 7 :(得分:0)

如果要在9PM之后到9Am之间的时间,可以使用以下条件。

if(cal.get(Calendar.HOUR_OF_DAY)> 20 || cal.get(Calendar.HOUR_OF_DAY)< 9)
{
    // do your stuffs
}

答案 8 :(得分:0)

class TimeRange {

    LocalTime from;
    LocalTime to;

    public TimeRange(LocalTime from, LocalTime to) {
        this.from = from;
        this.to = to;
    }

    public boolean isInRange(Date givenDate) {

        LocalTime givenLocalTime = getLocalDateTime(givenDate).toLocalTime();
        return givenLocalTime.isAfter(from) && givenLocalTime.isBefore(to);
    }

    public static LocalDateTime getLocalDateTime(Date date){

        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }
}