0

I am using customized Number Picker in my app to get the month and year as an input from the user. By selecting the Month in the number picker the month value should be saved as String and the year should be saved as an integer value. So I just want to get the complete Date format from the String month name and integer year value.

This is my customized month picker.

    final Dialog d = new Dialog ( getContext ( ) );
    d.setContentView ( R.layout.dialog );
    final NumberPicker monthNp = (NumberPicker) d.findViewById ( R.id.monthPicker );
    final NumberPicker yearNp = (NumberPicker) d.findViewById ( R.id.yearPicker );
    Button okDialog = (Button) d.findViewById ( R.id.ok_dialog );
    Button cancelDialog = (Button) d.findViewById ( R.id.cancel_dialog );
    monthNp.setMinValue ( 0 );
    monthNp.setMaxValue ( monthArray.length - 1 );
    monthNp.setDisplayedValues ( monthArray );
    monthNp.setWrapSelectorWheel ( false );
    monthNp.setValue ( imonth );
    monthNp.setOnValueChangedListener ( new NumberPicker.OnValueChangeListener ( ) {
        @Override
        public void onValueChange ( NumberPicker picker, int oldVal, int newVal ) {
            if ( oldVal != 0 ) {
                changed = 1;
                String  getMonthFromNp = monthArray[newVal];
            }
        }
    } );
}
if ( yearNp != null ) {
    yearNp.setMinValue ( year - 15 );
    yearNp.setMaxValue ( year );
    yearNp.setValue ( year );
    yearNp.setWrapSelectorWheel ( false );
    yearNp.setOnValueChangedListener ( new
            NumberPicker.OnValueChangeListener ( ) {
        @Override
        public void onValueChange ( NumberPicker picker, int oldVal,
                int newVal ) {
            if ( oldVal != 0 ) {
                changed = 1;
                int  getYearFromNp = yearNp.getValue ( );
            }
        }
    } );

    try{
        SimpleDateFormat monthFromNP = new SimpleDateFormat ( "MMMM" );
        Date month = monthFromNP.parse( getMonthFromNp );
        calendar = Calendar.getInstance ( );
        calendar.setTime ( month );
        calendar.set ( Calendar.YEAR, getYearFromNp );
        calendar.set ( Calendar.MONTH, +1 );
        calendar.set ( Calendar.DAY_OF_MONTH, 0 );
        calendar.set ( Calendar.DATE,
                calendar.getActualMinimum ( Calendar.DAY_OF_MONTH ) );
        calendar.set ( Calendar.HOUR_OF_DAY, 0 );
        calendar.set ( Calendar.MINUTE, 0 );
        calendar.set ( Calendar.SECOND, 0 );
        calendar.set ( Calendar.MILLISECOND, 0 );
        startDate = calendar.getTime ( );
        calendar.set ( Calendar.DATE,
                calendar.getActualMaximum ( Calendar.DAY_OF_MONTH ) );
        calendar.set ( Calendar.HOUR_OF_DAY, 23 );
        calendar.set ( Calendar.MINUTE, 59 );
        calendar.set ( Calendar.SECOND, 59 );
        calendar.set ( Calendar.MILLISECOND, 999 );
        endDate = calendar.getTime ( );
    } 
    catch ( ParseException e ) {
        e.printStackTrace ( );
    }
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Sathish V.A
  • 11
  • 1
  • 4
  • please add all the relevant code instead of just a photo – Nikos Hidalgo Dec 17 '18 at 12:58
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Dec 17 '18 at 13:35
  • Can’t you get the (month) number rather than the string from your picker? Would seem easier to me. Asking out of curiosity and not knowing Android GUI programming. – Ole V.V. Dec 17 '18 at 13:37
  • Yep, i am passing the months as string array, so while selecting the month in number picker it will return integer in the newVal=>9, so am passing the newVal my string array as month[9] and it will give the string array value "October". Even-though i get the month as integer format how to convert it to date format. – Sathish V.A Dec 17 '18 at 14:14

2 Answers2

1

java.time

    int monthVal = 9; // 0-based index, so 9 means October
    int yearVal = 2018;

    YearMonth ym = YearMonth.of(yearVal, Month.values()[monthVal]);
    System.out.println("Year and month selected: " + ym);

Output from this snippet is:

Year and month selected: 2018-10

It seems from your code that you need start and end of an interval comprising the selected month. If it can work for you, I suggest you get the half-open interval, that is, from start date, inclusive, to end date, exclusive. This saves you the oddities of setting a time to 23:59:59.999 and such. In this simple snippet I am setting the dates only since this is really enough to represent the interval:

    LocalDate startDateInclusive = ym.atDay(1);
    LocalDate endDateExclusive = ym.plusMonths(1).atDay(1);
    System.out.println("From " + startDateInclusive + " inclusive to "
            + endDateExclusive + " exclusive");

From 2018-10-01 inclusive to 2018-11-01 exclusive

If you need old-fashioned Date objects for some legacy API that you cannot change just now:

    Instant startInstantInclusive = startDateInclusive
            .atStartOfDay(ZoneId.systemDefault())
            .toInstant();
    Date oldfashionedDate = DateTimeUtils.toDate(startInstantInclusive);
    System.out.println("As old-fashioned Date: " + oldfashionedDate);

On my computer in Europe/Copenhagen time zone I got:

As old-fashioned Date: Mon Oct 01 00:00:00 CEST 2018

Do similarly for the end date.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. In this case only use Date oldfashionedDate = Date.from(startInstantInclusive) for concerting from Instant to Date.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Thanks for your reply and i'm having another doubt in my app. I will store data to the firebase firestore in daily basis. If the use wants to retrieve those datas by using the customized month and year picker(screenshot provided in the main question) by clicking "All" checkbox underneath the year and select the month as "June". So how do i query the datas which are all present in the June month for all the years?. – Sathish V.A Dec 21 '18 at 11:25
  • @SathishV.A I think that that’s a new question that you should ask as a new question. I’m also not sure that there’s enough information in this question to answer it. – Ole V.V. Dec 21 '18 at 11:28
0

Try this approach:

    int year = 2018;
    String month = "October";
    String str = month +" "+ year;

    SimpleDateFormat sdf = new SimpleDateFormat("MMMM yyyy");
    Date date = sdf.parse(str);
Anton Sarmatin
  • 505
  • 2
  • 8