2016-10-03 39 views
-2

我需要一個代碼,它可以將數字作爲輸入並將月份和月份作爲輸出。例如,如何從數字中獲取月份名稱

用戶輸入:33 輸出:2月2日

有人可以幫助我理解其中的邏輯這個問題。

+0

33如何與2月相關? 33應該代表一年中的哪一天? – Tunaki

+0

你需要弄清楚的第一件事是「33」是指「2月2日」。一旦你定義了翻譯邏輯,你就可以開始編寫執行該邏輯的代碼。 (注意:有些日期/時間庫在這裏可能會非常有用,而不是自己寫的。日期很難*。) – David

+2

'60'的輸出是什麼? '2月29日'或'火星1'? – Gendarme

回答

1

您可以使用DateTimeFormatter格式化您的日期和withDayOfYear(int dayOfYear)設定一年的第33天,作爲下一個:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d"); 
System.out.println(LocalDate.now().withDayOfYear(33).format(formatter)); 

或提出@Tunaki

System.out.println(Year.now().atDay(33).format(formatter)); 

輸出:

February 2 
+3

'Year.now()。atDay(33)',更直接。 – Tunaki

+0

@Tunaki thx輸入 –

0

替代品y,你可以假設一個非閏年並使用以下內容:

package com.company; 

public class Main { 

    public static void main(String[] args) { 
     String[] months = {"Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.", "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."}; 
     int[] daysinMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 
     int n = 33; // the input value 
     int i = 0; 

     n = n % 365; 

     while (n > daysinMonth[i]) { 
      n -= daysinMonth[i]; 
      i++; 
     } 
     System.out.println(months[i] + " " + n); 
    } 
} 
相關問題