简体   繁体   中英

how to get a month name from a number

I need a code that can takes a number as an input and tells month and date of the month as output. For example,

USer input: 33 Output: February 2

Can someone help me understand the logic to this problem.

You can use DateTimeFormatter to format your date and withDayOfYear(int dayOfYear) to set the 33th day of the year, as next:

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

or as proposed by @Tunaki

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

Output:

February 2

Alternatively, you could assume a non-leap year and use the following:

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

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