Setting time and date to date picker and time picker in android

后端 未结 5 1595
谎友^
谎友^ 2020-12-17 07:49

I am using a date picker and time picker in my application. I want to set the date and time when the page loads. Is this possible? How so?

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 08:14

    Using JodaTime

    JodaTime is an extremely popular and useful library for handling dates and times in Java. If you're not using it, I highly recommend taking a look at it.

    Here's a simple example of how I set a DatePicker and TimePicker from a DateTime object, which could be the current date or any date from the past or future (the attribute in this case is called inspected_at):

    DatePicker datePicker = (DatePicker) findViewById(R.id.inspected_at_date);
    TimePicker timePicker = (TimePicker) findViewById(R.id.inspected_at_time);
    
    DateTime inspected_at = DateTime.now()                // Typically pulled from DB.
    
    int year    = inspected_at.getYear() ;
    int month   = inspected_at.getMonthOfYear() - 1;      // Need to subtract 1 here.
    int day     = inspected_at.getDayOfMonth();  
    int hour    = inspected_at.getHourOfDay();
    int minutes = inspected_at.getMinuteOfHour();
    
    datePicker.updateDate(year, month, day);              // Set date.
    
    timePicker.setCurrentHour(hour);                      // Set time.
    timePicker.setCurrentMinute(minutes);
    

    Hope that helps.

    JP

提交回复
热议问题