3

I have an application where the user selects a date as well as a time (using DatePicker and TimePicker). Is there any way to combine all the values into one integer? Both the DatePicker and TimePicker return integers, if I add them up, will the value then be the selected date and time, or does it need to be done some other way?

The way I've been understanding date and time, is it gives the difference in milliseconds from a certain point. Based on that, I would guess that adding the amounts together would give the correct time (taking into account the different starting times of the various methods).

Thanks!

1 Answer 1

6

You can use a Calendar, set the components then get the date.

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 37);
cal.set(Calendar.DAY_OF_MONTH, 13);
cal.set(Calendar.MONTH, Calendar.JANUARY);

Date d = cal.getTime();
long time = cal.getTimeInMillis();
5
  • 1
    This solves your problem. I would post an answer, but I just want to expand on this good answer. Regardless which Calendar library you use, generally time in milliseconds wouldn't be the same as datetime in milliseconds. And even if you did, its more than likely the milliseconds you get back incorporates the date as well (Java7 Time class is a wrapper to Date). I'd recommend JodaTime for heavy calendar usage. But if all you wanna do is combine the two values into a single value the above will suffice. Oh I wouldn't do this though cal.set(Calendar.MONTH, Calendar.JANUARY); use your month val.
    – Andy
    Commented Jan 13, 2015 at 20:05
  • This seems to be working so far (I think). It's returning a certain number, although I haven't reached the part of my program where I see if that number is the one I'm looking for. Thanks! Commented Jan 13, 2015 at 20:52
  • @Andy I used the constant because unlike day of the month, calendar months start at 0, so it can cause a bit of trouble if you expect 1 to be January.
    – Dave S
    Commented Jan 13, 2015 at 21:36
  • Pretty sure the android pickers return the month 0 based, so he should be good :)
    – Andy
    Commented Jan 13, 2015 at 21:37
  • Ah, I haven't used those. In my case was I was parsing the date from a string representation.
    – Dave S
    Commented Jan 13, 2015 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.