其他分享
首页 > 其他分享> > 根据输入年月打印该月的全部日期及星期几

根据输入年月打印该月的全部日期及星期几

作者:互联网


```java
package com.offcn;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class test2 {

    public static void main(String[] args) {
        try {
            calendar(2021,07);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private static void calendar(int m, int n) throws ParseException {
        int ds = getdays(m, n);
        System.out.print("[");
        for (int i=1;i<=ds;i++){
            Integer d = new Integer(i);
            System.out.print("{\""+i+"\":\""+getweek(m,n,i)+"\"}");
            if (i!=ds){
                System.out.print(",");
            }
        }
        System.out.print("]");
    }

    private static int getdays(int m, int n) {
        int d=0;
        switch (n){
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                d=31;break;
            case 4:
            case 6:
            case 9:
            case 11:
                d=30;break;
            case 2:
                if (m%4==0&&m%100!=0){
                    d=29;
                }else {
                    d=28;
                }
                break;
                default:
                    System.out.println("错误");
        }
        return d;
    }

    private static String getweek(Integer m, Integer n, Integer d) throws ParseException {
        String time=m.toString()+"-"+n.toString()+"-"+d.toString();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(time);
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("E");
        String format = simpleDateFormat1.format(parse);
        if ("星期一".equals(format)){
            format="Mo";
        }else if ("星期二".equals(format)){
            format="Tu";
        }else if ("星期三".equals(format)){
            format="We";
        }else if ("星期四".equals(format)){
            format="Th";
        }else if ("星期五".equals(format)){
            format="Fr";
        }else if ("星期六".equals(format)){
            format="Sa";
        }else
            format="Su";
        return format;
    }
}

输出结果:
[{"1":"Th"},{"2":"Fr"},{"3":"Sa"},{"4":"Su"},{"5":"Mo"},{"6":"Tu"},{"7":"We"},{"8":"Th"},{"9":"Fr"},{"10":"Sa"},{"11":"Su"},{"12":"Mo"},{"13":"Tu"},{"14":"We"},{"15":"Th"},{"16":"Fr"},{"17":"Sa"},{"18":"Su"},{"19":"Mo"},{"20":"Tu"},{"21":"We"},{"22":"Th"},{"23":"Fr"},{"24":"Sa"},{"25":"Su"},{"26":"Mo"},{"27":"Tu"},{"28":"We"},{"29":"Th"},{"30":"Fr"},{"31":"Sa"}]

标签:星期,Fr,Tu,java,int,打印,Th,Sa,输入
来源: https://blog.csdn.net/l_Love_Study/article/details/119054133