简体   繁体   中英

How to get month according to day of year

I have input like 34 which means its 3rd day of February , but how to determine programatically in Java by taking day of year and getting month name or month month value like 0 for January is there any API in Java that handles this. I searched in Calendar class but did not found any.

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DAY_OF_YEAR, 34);
    System.out.println(cal.get(Calendar.MONTH));

Will return 1 (as Months start with 0).

Try this

Calendar cal = Calendar.getInstance();
cal.set(2014, 0, 1);
cal.add(Calendar.DAY_OF_YEAR, 34);

Re-inventing wheel :-(

package com.test;

public class FindMonthByTotalNumberOfDays {
    public static void main(String[] args) {
        int input = 89;
        int monthDigit = extractMonthDigit(input);
        System.out.println("Total number of days " + input + " lies in month " + monthDigit + ".");
    }

    private static int extractMonthDigit (int totalNumberOfDays) {
        int result = -1;
        if(isInBetween(1, 31, totalNumberOfDays)) result = 0;
        else if(isInBetween(32, 59, totalNumberOfDays)) result = 1;
        else if(isInBetween(60, 90, totalNumberOfDays)) result = 2;
        else if(isInBetween(91, 120, totalNumberOfDays)) result = 3;
        else if(isInBetween(121, 151, totalNumberOfDays)) result = 4;
        else if(isInBetween(152, 181, totalNumberOfDays)) result = 5;
        else if(isInBetween(182, 212, totalNumberOfDays)) result = 6;
        else if(isInBetween(213, 243, totalNumberOfDays)) result = 7;
        else if(isInBetween(244, 274, totalNumberOfDays)) result = 8;
        else if(isInBetween(275, 304, totalNumberOfDays)) result = 9;
        else if(isInBetween(305, 335, totalNumberOfDays)) result = 10;
        else if(isInBetween(336, 366, totalNumberOfDays)) result = 11;
        return result;
    }

    private static boolean isInBetween(int min, int max, int days) {
        boolean isInBetween = false;
        if(days >= min && days <= max) {
            isInBetween = true;
        }
        return isInBetween;
    }
}
Calendar    calendar    = Calendar.getInstance();

calendar.set( Calendar.DAY_OF_YEAR, dayOfYear_ );

Date                resultDate      = calendar.getTime();
SimpleDateFormat    stringFormat    = new SimpleDateFormat( "dd-MMM" );
String              result          = stringFormat.format( resultDate );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM