1. 程式人生 > 實用技巧 >getDaysByMonth獲取當前月自然天數

getDaysByMonth獲取當前月自然天數

程式碼:

package jc_wis;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 測試類
 * @author wang-xiaoming
 *
 */
public class TestDate {
    public static void main(String[] args) {
        System.
out.println("2020-12 : " + getDaysByMonth("2020-12")); System.out.println("2021-01 : " + getDaysByMonth("2021-01")); System.out.println("2021-02 : " + getDaysByMonth("2021-02")); } public static final String FORMAT_SHORTER = "yyyy-MM"; /** * 日期格式化 * @param date * @param pattern * @return
*/ public static Date parse(String date, String pattern) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { return sdf.parse(date); } catch (ParseException e) { e.printStackTrace();
return null; } } /** * 返回指定某一年某一月的所有日期號 * @param date * @return */ public static List<Integer> getDaysByMonth(String date){ Calendar c = Calendar.getInstance(); c.setTime(parse(date, FORMAT_SHORTER)); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); List<Integer> list = null; if(month >= 0 && month <= 11){ list = new ArrayList<>(31); c = Calendar.getInstance(); c.set(year, month, 1); int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH); for (int i = 0; i <= lastDay; i++) { list.add(i); } } return list; } }

結果:

2020-12 : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
2021-01 : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
2021-02 : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]