2014-02-17 32 views
1

日獲得一個月我有一個像34輸入,這意味着它的3rd day of February,而是如何通過採取day of year並獲得month name或一個月month value like 0 for January編程確定在Java中有沒有在Java中處理這個任何API。我搜索了Calendar class,但沒有找到任何。如何根據今年

+0

你可以自己實現它 –

+3

剛開始1月1日,並添加'DAYOFYEAR - 1'天... –

+0

您還需要知道您是否處於閏年 – Henry

回答

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

將返回1(因爲月份以0開始)。

+1

此帳戶是否爲閏年? – Adarsh

+0

如果您相應地設置年,則爲。GetInstance()會給你包括當年的當前日期。 –

1

試試這個

Calendar cal = Calendar.getInstance(); 
cal.set(2014, 0, 1); 
cal.add(Calendar.DAY_OF_YEAR, 34); 
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; 
    } 
} 
+0

將不適用於閏年。 :) – Vishrant

+0

試圖快速寫一個代碼,同意不考慮閏年,也只是印刷數量需要映射到實際月份等...感謝Vishrant。 –

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