10

I have two String variables - time1 and time2. Both contain value in the format HH:MM. How can I check:

  1. If the current time is within time1 and time2?
  2. time1 will happen in the nearest hour?

Upd. I've implemented the following to convert time1 to Date format. But it uses depreciated methods:

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());
Peter O.
  • 32,158
  • 14
  • 82
  • 96
LA_
  • 19,823
  • 58
  • 172
  • 308
  • If I use `java.sql.Time`, then I can easily get time value from my strings - `Time.valueOf(time1).getTime()`. But how should I get current time in the same format (`long`)? – LA_ Jun 16 '11 at 19:45

9 Answers9

26
  • Convert the two strings to Date objects (which are also time objects) Create a new Date object.
  • This will contain the current time.
  • Use the Date.before() and Date.after() methods to determine if you are in the time interval.

EDIT: You should be able to use this directly (and no deprecated methods)

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);
    }
}
Caspar Harmer
  • 8,097
  • 2
  • 42
  • 39
  • @CaspNZ, I've tried to do so, but didn't get how to convert string in my format (not like *20081013T160000Z*) to `Date`. Can you help me with this? – LA_ Jun 16 '11 at 19:41
  • @DArkO - it looks like some of the Date _constructors_ are deprecated, but using a parser in my example above isn't deprecated - I think this is still supported. – Caspar Harmer Jun 16 '11 at 19:55
  • @CaspNZ, ok, I have my strings now as Date: Jan 1, 1970 + my time1. How can I get current time with date equal to Jan 1, 1970 also? – LA_ Jun 16 '11 at 20:07
  • make a new inputParser with a string of 'yyyy-MM-dd' and parse in '1970-01-01'. As you've left the time off, it'll fill it with the current time for you. – Caspar Harmer Jun 16 '11 at 20:19
  • That does seem a little hackish, however. Another way would be to create a new empty date and extract the current Date and Year values from it and add them to your initial dates when you parse them in (you'd have to change your input format string). – Caspar Harmer Jun 16 '11 at 20:21
  • @CaspNZ, first approach (_make a new inputParse ..._) doesn't work - the time returned is 00:00:00. – LA_ Jun 17 '11 at 19:19
  • @CaspNZ, with regards to the second approach - I didn't manage to implement that (for ex., how to add leading zeroes?), so I've implemented that in a different way - see the code in the question. But I don't like such approach. And, is it fast enough? – LA_ Jun 17 '11 at 19:39
  • Ok check out my new example - I think this one is going to work well. And it should be pretty fast. – Caspar Harmer Jun 17 '11 at 20:17
  • And how would this work if the user picked, say, 5am for the start time and 3 am for the end time?? – benbeel Nov 03 '11 at 03:35
  • Well, this is an example solution, you might want to evaluate both cases for it to be completely accurate. It's not hard to change the code to handle this situation. Perhaps a better function name would have been "isNowBetween(startTime, endTime)" – Caspar Harmer Nov 03 '11 at 04:20
  • @CaspNZ thanks for your help. it works for me.. thanks again. but I have a query, in your condition why did you just comparing the constant time (datecompareOne) with the variable time (date) ?.. What if I used this ((date.after(datecompareOne)) && (date.before(datecomparetwo))) – M A. Jun 05 '14 at 05:28
  • note that you have to use `HOUR_OF_DAY` if you want 24 hour format – He Yifei 何一非 Aug 03 '16 at 06:13
  • how to get Am and Pm time difference? write now not able to difference between day and night timing. – Amandeep Rohila Jan 31 '17 at 10:09
  • Change the input format. Look up the input format for am and pm ( I think it's just 'HH:mm a'. Then parse as usual. I haven't been using Java for a long time, so can't help you anymore here. – Caspar Harmer Jan 31 '17 at 17:25
5

This is what I used as simple function and it worked for me:

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

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

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

        if (time1.before(d) && time2.after(d)) {
            isBetween = true;
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return isBetween;
}
Nitin Patel
  • 1,605
  • 13
  • 31
kinsley kajiva
  • 1,840
  • 1
  • 21
  • 26
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 ");
}

Don't forget to surrounded with a try catch block

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Osama Ibrahim
  • 995
  • 10
  • 13
3

if you want time between after 9PM to before 9Am you can use following condition..

if(cal.get(Calendar.HOUR_OF_DAY)> 20 || cal.get(Calendar.HOUR_OF_DAY)< 9)
{
    // do your stuffs
}
Abhay Pratap
  • 1,886
  • 11
  • 15
2

Look into the Calendar class. It has the methods to support what you are asking. Date is deprecated and not recommended to use.

Here is the link to the API. Calendar

About the usage. First you need to call Calendar.getInstance() to create a calendar object. Next you need to Set the two fields using cal.set(Calendar.HOUR, your hours) and Calendar.MINUTES the same way. Next you can call the compare function, before or after functions to get the desired info. Also you can get an instance with the current time in the current locale.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
DArkO
  • 15,880
  • 12
  • 60
  • 88
1

For example if you want to compare time between 11pm to 6am for calculating extra night fare for any vechicle. then following code will help you.

// Code

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

}`
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();
        }
Praveen
  • 430
  • 3
  • 11
0

As of now, I am thinking about the following approach:

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;

So, I'll need to compare just integer values clTime and nowTime.

LA_
  • 19,823
  • 58
  • 172
  • 308
  • If checking for a time within a *range*, you'll need to account for the overflow scenario. That is, the start time is later in the day than the stop time. Actually this situation is true regardless of the coding approach. I'm starting to like your solution for recurring daily time range checks. – pmont Aug 18 '13 at 11:21
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());
    }
}
Kanagavelu Sugumar
  • 18,766
  • 20
  • 94
  • 101