日期组装 (如:2020年1月1日、二〇二〇年一月一日、1/1/2020)

package com.yhcookie.basedemo.util;

import org.springframework.util.StringUtils;
import java.time.LocalDate;

/**
 * 日期组装测试
 * @author yhcookie
 * @date 2020/5/2 10:20
 */
public class DateWrapperTest {

    public static void main(String[] args){
        // 2020-01-01
        LocalDate currentDate = LocalDate.now();

        /**
         * ey:currentDateStr = "2020-01-01"
         *     currentYearStr = "2020"
         *     currentMonthStr = "1"
         *     currentDayStr = "1"
         */
        String currentDateStr = currentDate.toString();
        String currentYearStr = String.valueOf(currentDate.getYear());
        String currentMonthStr = String.valueOf(currentDate.getMonth().getValue());
        String currentDayStr = String.valueOf(currentDate.getDayOfMonth());
        
        // 2020年1月1日
        String chineseCurrentDate 
                = currentYearStr + "年" + currentMonthStr + "月" + currentDayStr + "日";
        // 二〇二〇年一月一日
        String fullChineseCurrentDate
                = numberStrToChineseStr(currentYearStr) + "年" + numberStrToChineseStr(currentMonthStr) + "月" + numberStrToChineseStr(currentDayStr) + "日";
        // 1/1/2020
        String enCurrentDateStr 
                = currentDayStr + "/" + currentMonthStr + "/" + currentYearStr;
    }

    /**
     * 数字字符串转汉字字符串
     * @return
     */
    private static String numberStrToChineseStr(String numberStr){
        // "" || null || 非全数字
        if (StringUtils.isEmpty(numberStr) || !numberStr.matches("^[0-9]+")){
            return numberStr;
        }

        String chineseStr = "";
        char[] numberStrCharArray = numberStr.toCharArray();
        for (char c : numberStrCharArray) {
            switch (c){
                case '0':
                    chineseStr += "〇";
                    break;
                case '1':
                    chineseStr += "一";
                    break;
                case '2':
                    chineseStr += "二";
                    break;
                case '3':
                    chineseStr += "三";
                    break;
                case '4':
                    chineseStr += "四";
                    break;
                case '5':
                    chineseStr += "五";
                    break;
                case '6':
                    chineseStr += "六";
                    break;
                case '7':
                    chineseStr += "七";
                    break;
                case '8':
                    chineseStr += "八";
                    break;
                case '9':
                    chineseStr += "九";
                    break;
                default:
                    break;
            }
        }
        return chineseStr;
    }
}

 

你可能感兴趣的:(日期组装 (如:2020年1月1日、二〇二〇年一月一日、1/1/2020))