Search code examples
javaandroiddatetimeunix-timestamp

Convert integer dates/times to unix timestamp in Java?


This mainly applies to android, but could be used in Java. I have these listeners:

int year, month, day, hour, minute;
// the callback received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                year = year;
                month = monthOfYear;
                day = dayOfMonth;
            }
        };
// the callback received when the user "sets" the time in the dialog
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
    new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            hour = hourOfDay;
            minute = minute;
        }
    };

How could I convert int year, month, day, hour, minute; to a unix timestamp? Is this possible without the Date class?


Solution

  • Okay, use Calendar then, since that's preferred to Date anyway:

    int componentTimeToTimestamp(int year, int month, int day, int hour, int minute) {
    
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);
        c.set(Calendar.DAY_OF_MONTH, day);
        c.set(Calendar.HOUR, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
    
        return (int) (c.getTimeInMillis() / 1000L);
    }
    

    Calendar won't do any computations until getTimeMillis() is called and is designed to be more efficient than Date.