0

I have three 'long' variables: start, end & testtime.

long start = 1412801340000         //(means 10/8/14 4:49 PM in UTC time) 
long end= 1412808540000            //(means 10/8/14 6:49 PM in UTC time)

long testtime = 1447195740000      //(means 11/10/15 5:49 PM in UTC time)

I want to test whether the TIME OF DAY (do not care about the date, month & year at all) in testtime is between start and end or not. How can I do this?

Basically, I just want to extract the Time of Day from each of the long variables, and then check if testtime falls in between *start" & end.

user1406716
  • 9,565
  • 22
  • 96
  • 151
  • Very similar to: [How to get the number of milliseconds elapsed so far today](https://stackoverflow.com/q/6476065/642706) – Basil Bourque Feb 10 '18 at 04:49

5 Answers5

2

You can use like this below code just give the millesecond as your input to the date and convert as your date format

    Date date = new Date(System.currentTimeMillis()); //Input your time in milliseconds
    String yourDesiredDateValue = new SimpleDateFormat("dd MMM yyyy hh:mm a").format(date);

"dd MMM yyyy hh:mm a" ----> your date format

Naveen Kumar Kuppan
  • 1,424
  • 1
  • 10
  • 12
1

Create java.util.Date objects and then use Date.getMinutes and Date.getHours etc for the comparison.

And please note, this looks like a very simple task, but there are pitfalls, for example daylight saving and leap year when the risk are that you will experience some strange errors in your code. To avoid this you need to specify timezone and such. The Calendar class can do this for you.

I know I complicate things for you now, but date&time bugs can be a real nuance, especially since they only pop up now and then.

AndersG
  • 365
  • 4
  • 12
1
Calendar cStart = Calendar.getInstance();
cStart.setTimeInMillis(start);
Calendar cEnd = Calendar.getInstance();
cEnd.setTimeInMillis(end);
Calendar cTest = Calendar.getInstance();
cTest.setTimeInMillis(testtime);

if(cStart.before(cTest) && cEnd.after(cTest)) {
    // testtime is between start and end
}
Boban S.
  • 1,662
  • 13
  • 16
  • Not quite, but your code helped, so will be marking this as the answer. In my code, the date and year and month are different, only want to compare time (hr, mins, secs). Thank you very much for your input. (& thanks to other too - learnt something from each answer) – user1406716 Oct 09 '14 at 04:55
  • I'm glad that I helped. You can reset date in calendar or set it the same so it works only with time. – Boban S. Oct 09 '14 at 07:49
  • FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. Much of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Feb 10 '18 at 06:09
1

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This Answer left intact for history.

LocalTime

Assuming those milliseconds are a count since the Unix epoch (beginning of 1970), and assuming you care about time-of-day as defined by UTC, then you should use either Joda-Time or the java.time package in Java 8. Both of those frameworks offer a LocalTime class to represent a time-of-day without a date or time zone.

Joda-Time

Here is code in Joda-Time version 2.4. We first get a date-time object in UTC from your long number, then convert to a time-only value while losing the date and time zone information.

long start = 1412801340000         //(means 10/8/14 4:49 PM in UTC time) 
long end= 1412808540000            //(means 10/8/14 6:49 PM in UTC time)
long testtime = 1447195740000      //(means 11/10/15 5:49 PM in UTC time)

LocalTime startLocalTime = new DateTime( start, DateTimeZone.UTC ).toLocalTime();
LocalTime endLocalTime = new DateTime( end, DateTimeZone.UTC ).toLocalTime();
LocalTime testLocalTime = new DateTime( testtime, DateTimeZone.UTC ).toLocalTime();

boolean isBetween = ( testLocalTime.isAfter( startLocalTime ) ) && ( testLocalTime.isBefore( endLocalTime ) );

In real-life I would first assign the DateTime instances to a variable before converting to LocalTime objects to facilitate debugging. Here, the compactness makes for a better demo.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

tl;dr

Interval.of( 
    Instant.ofEpochMilli( 1_412_801_340_000L ) ,  // 2014-10-08T20:49:00Z
    Instant.ofEpochMilli( 1_412_808_540_000L )    // 2014-10-08T22:49:00Z
).contains(
    Instant.ofEpochMilli( 1_447_195_740_000L )    // 2015-11-10T22:49:00Z
)

false

java.time

If you wish to consider those values as date-times in UTC, then the modern approach uses the java.time classes that supplanted the troublesome old Date & Calendar classes.

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Sample data errors/ambiguity

By the way, your date-time description of your sample count-of-milliseconds-since-start-of-1970-UTC are incorrect. See my output below. You seem to have an offset affecting your numbers, an offset of 4 hours in the first two and then 5 hours in the last one, probably due to to a "fall-back" change in Daylight Saving Time (DST). This demonstrates why tracking time as a count-from-epoch is such a poor idea, fraught with problems of ambiguity and uncaught errors. I suggest always serializing such moments to text using standard ISO 8601 formats.

Instant start = Instant.ofEpochMilli( 1_412_801_340_000L );  // 2014-10-08T20:49:00Z (not 10/8/14 4:49 PM in UTC time)
Instant stop = Instant.ofEpochMilli( 1_412_808_540_000L );   // 2014-10-08T22:49:00Z (not 10/8/14 6:49 PM in UTC time)
Instant test = Instant.ofEpochMilli( 1_447_195_740_000L );   // 2015-11-10T22:49:00Z (not 11/10/15 5:49 PM in UTC time)

See that code run live at IdeOne.com.

start.toString(): 2014-10-08T20:49:00Z

stop.toString(): 2014-10-08T22:49:00Z

test.toString(): 2015-11-10T22:49:00Z

Compare

Compare Instant objects with isBefore, isAfter, and equals.

Generally the best approach to handling spans of time is known as Half-Open, where the beginning is inclusive and the ending is exclusive. So, for example, a day starts at the first moment of the day and runs up to, but does not include, the first moment of the following day.

boolean isTestWithinRange = 
    ( test.equals( start ) || test.isAfter( start ) )
    &&
    test.isBefore( stop ) 
;

A shorter way of asking "is equal to or later than" is "is not before".

boolean isTestWithinRange = 
    ( ! test.isBefore( start ) )
    &&
    test.isBefore( stop ) 
;

Even shorter, use the org.threeten.extra.Interval class found in the ThreeTen-Extra project, a library you can add to your Java project. Not sure if this yet works in Android.

Interval interval = Interval.of( start , stop ) ;
boolean isTestWithinRange = interval.contains( test ) ;

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.

With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154