1

I'm building a little android app where the user would choose a start time for some operation.

I'm using the TimerPickerDialog:

mTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
        startTimeHours = selectedHour;
        startTimeMinutes = selectedMinute;
}, hour, minute, is24hours);

and when a time is selected it returns an int for the hour and int for the minutes, which I save as a global variable.

later in my app I want to convert those numbers into a Time object which I can then use to see if the current time is bigger or smaller than the time represented in that class.

what I've done is this:

Time tStart = new Time(startTimeHours, startTimeMinutes, 0);

but eclips says that this constructor is deprecated. however the constructor that takes long is does not seem to be deprecated.

I looked around and in one post someone recommended to use the Calendar object - but I couldn't figure it out - how to get a new instance of it and set my time. it looks like an overhead for just containing the time.

What is the best practice for such a scenario? if I need to use the constructor that accepts the long variable - how do I convert my 2 integers to that long value?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
developer82
  • 13,237
  • 21
  • 88
  • 153

3 Answers3

3

EDIT2:

This is how you would create two Date objects with different times and compare them afterwards:

Calendar calendar = Calendar.getInstance(); // By default the date and time is set to now

// Create first date
calendar.set(Calendar.HOUR_OF_DAY, 20);
calendar.set(Calendar.MINUTE, 5);
Date dateOne = calendar.getTime();

// Create second date
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 36);
Date dateTwo = calendar.getTime();

// With before() you can check if a Date is before some other date
if(dateOne.before(dateTwo)) {
    // dateOne is before dateTwo
} else {
    // dateTwo is before dateOne
}

You can also use after() to check if some Date is after some other Date.


EDIT:

That Long value you speak of in the last paragraph of your question is epoch time in milliseconds. You really should not use this Time class from the framework. I think you mean this one? You should use the solution I posted below.


ORIGINAL ANSWER:

I mostly tend to use Date objects as containers. And the best practice to create Date instances is to use a Calendar object. Try something like this:

// We get a Calendar instance with getInstance();
Calendar calendar = Calendar.getInstance();

// Now we set the date we want.
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.MONTH, 4);  // Be carefull, months start at 0. January = 0, Feburary = 1, March = 2,...
calendar.set(Calendar.DAY_OF_MONTH, 29);
calendar.set(Calendar.HOUR_OF_DAY, 20);
calendar.set(Calendar.MINUTE, 5);

// And finally we create the `Date` instance with getTime()
Date date = calendar.getTime();

// You can also do the reverse and set the time in a `Calendar` instance from a `Date` instance.
calendar.setTime(date);

This is pretty simple and Calendar is pretty powerful, but I don't think that this is suitable for you. Because this solution creates a Date object. As such it stores much more than just hours and minutes.

You have to decide if that is applicable to your situation. If you really just want to store hours and minutes I suggest you create a custom Time class like this:

public class Time {

    private int minute;
    private int hour;

    public int getMinute() {
        return minute;
    }

    public void setMinute(int minute) {
        this.minute = minute;
    }

    public int getHour() {
        return hour;
    }

    public void setHour(int hour) {
        this.hour = hour;
    }
}

If necessary you can also add validation and calculations to this Time class, but again this all depends on what you want do to.

We could give you a more accurate answer If you give us more information about what kind of time values you need to store, more precisely if any date information has to be stored too?

Xaver Kapeller
  • 49,491
  • 11
  • 98
  • 86
  • What I need to do in my app is take the current time and check of it's bigger or smaller or equal to the time the user selected. How can I make such a comparison? – developer82 May 30 '14 at 13:26
  • I assume you only mean comparing different times on the same day? I will edit my answer. – Xaver Kapeller May 30 '14 at 13:27
1

Rather than spend time making classes that have limited use, like a Time object which really doesn't have any use except in the context of a containing Date, focus on making Dates easier to manipulate maybe.

Using the set methods on the calendar is a serious drag and it's ugly. The Date/Time stuff got blown up in Java 8 in part because of this.

That said, I got kind of fed up a while ago and made a DateBuilder which uses the fluent builder design pattern to let you easily construct dates using an approach like this:

Date newDate = new DateBuilder().hour(10).minute(20).build();

Eventually I added a bunch of other conveniences that are a nuisance like giving me midnight, or letting me just add time. The thing that really sucks about the way Dates work in Java is that you find yourself writing a lot of code, it's ugly, and it greatly decreases the readability of the surrounding code. Builder compartmentalizes that.

The part that surprises people is how easy it is to just jump into your own class and add something like an add function, e.g.:

new DateBuilder(new Date()).addDays(3).build();

I played around with the new Date stuff in 8 and it is nicer. Joda is nicer too, but the funny thing is ultimately I ended up not liking Joda that much because while it was nicer, it just brought some of the same things into the code, and it failed one of the most important tests of a library you adopt: I kept having to go back and read the docs each time I used it. Using Categories in Objective-C convinced me that it's often best to fashion the top layer of the code you will be touching yourself, in part because you are more likely to make something you will use fluidly (hence the name), but also because it's a quasi-DSL: if I were to do programming in a different domain, I might want a different DateBuilder that emphasized other things.

Rob
  • 11,446
  • 7
  • 39
  • 57
1

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Solution using java.time, the modern API:

import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        // Sample startTimeHours and startTimeMinutes (to be obtained from
        // TimerPickerDialog in your case
        int startTimeHours = 19;
        int startTimeMinutes = 0;

        LocalTime startTime = LocalTime.of(startTimeHours, startTimeMinutes);

        LocalTime now = LocalTime.now().truncatedTo(ChronoUnit.MINUTES);

        System.out.println(
                            now.isAfter(startTime) ?  "Past"    :
                            now.isBefore(startTime) ? "Future"  :
                                                      "Present"
        );
    }
}

Output:

Present

Learn more about java.time, the modern Date-Time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110