java代码枚举实现月份缩写字符串和整形转换

package com.example;
import java.util.Arrays;
public enum MonthEnum {
    January(1, "Jan"),
    February(2, "Feb"),
    March(3, "Mar"),
    April(4, "Apr"),
    May(5, "May"),
    June(6, "Jun"),
    July(7, "Jul"),
    August(8, "Aug"),
    September(9, "Sept"),
    October(10, "Oct"),
    November(11, "Nov"),
    December(12, "Dec");
    private final int code;
    private final String name;

    MonthEnum(int code, String name) {
        this.code = code;
        this.name = name;
    }

    public int getCode() {
        return code;
    }

    public String getName() {
        return name;
    }
/**
     * @param code
     * @return
     */
    public static MonthEnum getEnumByCode(int code) {
        for (MonthEnum e : MonthEnum.values()) {
            if (e.getCode() == code) {
                return e;
            }
        }
        return null;
    }
/**
     * @param name
     * @return code
     */
    public static int getCodeByName(String name) {
        for (MonthEnum e : MonthEnum.values()) {
            if (e.getName().equalsIgnoreCase ( name) ) {
                return e.getCode() ;
            }
        }
        return 0;
    }
    public static int valueByName(String name) {
		MonthEnum e=Arrays.stream(MonthEnum.values()).filter(ec -> ec.getName().equalsIgnoreCase ( name)).findFirst().orElse(null);
		if(e==null){            
             return 0;
        }else{
			return e.getCode() ;
        }       
    }
    
}

调用的测试代码

package com.example;

import java.time.Month;
import java.time.format.TextStyle;
import java.util.Locale;
//import com.example.MonthEnum;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        java.time.Month m=java.time.Month.of(9);
        System.out.print( "month:");
        System.out.println( m. getDisplayName(TextStyle.SHORT,Locale.ENGLISH));
        m=Month.valueOf("OCTOBER");
        System.out.print( "month:");
         System.out.println( m.getValue());
         System.out.println( m. getDisplayName(TextStyle.SHORT,Locale.ENGLISH));
         MonthEnum e=MonthEnum.getEnumByCode(10);
         System.out.print( "new month:");
         System.out.print( e.getCode());
         System.out.println( e.getName());
         System.out.print( "new code:");
         System.out.println( MonthEnum.valueByName("oct"));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值