2016-10-03 35 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); 
    } 
} 
相关问题