java获取字符串年月,Java从整数中获取月份字符串

Is there a better way to compact this method i.e. reduce the cyclomatic complexity by avoid the switch cases?

String monthString;

switch (month) {

case 1: monthString = "January"; break;

case 2: monthString = "February"; break;

case 3: monthString = "March"; break;

case 4: monthString = "April"; break;

case 5: monthString = "May"; break;

case 6: monthString = "June"; break;

case 7: monthString = "July"; break;

case 8: monthString = "August"; break;

case 9: monthString = "September"; break;

case 10: monthString = "October"; break;

case 11: monthString = "November"; break;

case 12: monthString = "December"; break;

default: monthString = "Invalid month"; break;

}

System.out.println(monthString);

解决方案

Try:

import java.text.DateFormatSymbols;

monthString = new DateFormatSymbols().getMonths()[month-1];

Alternatively, you could use SimpleDateFormat:

import java.text.SimpleDateFormat;

System.out.println(new SimpleDateFormat("MMMM").format(date));

(You'll have to put a date with your month in a Date object to use the second option).

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值