如何根据一年中的某一天获得月份

时间:2014-02-17 10:39:19

标签: java java-ee calendar

我的输入类似于34,意味着3rd day of February,但如何通过day of year获取month name或月month value like 0 for January来以编程方式确定Java中有任何API可以处理这个问题。我在Calendar class搜索但没有找到任何。

4 个答案:

答案 0 :(得分:3)

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

将返回1(月份从0开始)。

答案 1 :(得分:1)

试试这个

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

答案 2 :(得分:0)

重新发明轮子: - (

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;
    }
}

答案 3 :(得分:0)

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 );