2014-04-02 157 views
1

我需要将缩短的月份名称转换为较长的表示(例如“Dec” - >“December”)。月份名称是一个字符串,我宁愿不先将其转换为日期对象。将缩短的月份名称转换为较长的月份名称

有没有简单的方法来做到这一点?

编辑: 我的问题是与在MySQL中插入“Dec”作为表名(当然会引发语法错误)有关,对于我的用例,更改此值比让mysql更好命令改变它。

+1

发布您的试用代码 – newuser

+2

简单的方法是先将其转换为日期对象。否则,'if-else'或'switch'是你的选项 – Baby

+1

ladder'if-else' ... –

回答

3

最明显的方法是:

if (month.equalsIgnoreCase("Jan")) 
    month = "January"; 
else if (month.equalsIgnoreCase("Feb")) 
    month = "February"; 
// and so on... 

这也可以用一个switch表示,如果你喜欢:

switch (month.toLowerCase()) { 
case "jan": month = "January"; break; 
case "feb": month = "February"; break; 
// and so on... 
} 

或者,更宽容版本:

if (month.toLowerCase().startsWith("Jan")) 
    month = "January"; 
// and so on... 

我想你可以首先将它们存储在一个地图:

Map<String,String> monthNames = new HashMap<String,String>(); 
monthNames.put("jan", "January"); 
monthNames.put("feb", "February"); 
// and so on... 

String shortMonth = "Jan"; 
String month = monthNames.get(shortMonth.toLowerCase()); 
if (month == null) 
    month = shortMonth; 

使用的地图让你轻松地添加翻译成其他语言,我想。您也可以自动使用当前的语言环境,Russell Zahniser's很好的答案。

似乎没有太多理由将它们解析为日期和返回(尽管如果你这样做,请参阅newuser's answer)。

有很多方法可以做到这一点。

+1

最初我使用HashMap解决方案,尽管switch语句解决方案对我的用例最适合。谢谢! –

+0

'if(month.toLowerCase()。startsWith(“Jan”))'很确定这是一个错字。 – primo

2

试试这个,使用这种格式来获得的全部价值MMMM

 String month = "Dec"; 
     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM"); 
     try 
     { 
      Date date = simpleDateFormat.parse(month); 
      simpleDateFormat = new SimpleDateFormat("MMMM"); 
      System.out.println(simpleDateFormat.format(date)); 
     } 
     catch (ParseException ex) 
     { 
      System.out.println("Exception "+ex); 
     } 
+0

他说他不想使用日期对象... – StephenButtolph

2

要做到这一点使用为用户配置的语言环境的月份名称:

// Set up a lookup table like this: 

Map<String,String> shortToLong = new HashMap<String,String>(); 
DateFormatSymbols symbols = new DateFormatSymbols(); 

for(int i = 0; i < symbols.getMonths().length; i++) { 
    shortToLong.put(symbols.getShortMonths()[i], symbols.getMonths()[i]); 
} 

// Then use like this: 

String longMonth = shortToLong.get(shortMonth); 
+0

+1这很好,因为它服从当前的语言环境。如果情况对短名称无关紧要的话,可能会在里面抛出一些'toLowerCase()'。 –

2

这样做的另一种方法是用长月份名称开始,然后缩写每一个,看看哪一个匹配给定输入。

String s="MAR"; 
String months[]={"January","February","March","April","May","June","July","August","September","October","November","December"}; 
for(String i : months) { 
    if(i.substring(0,3).equalsIgnoreCase(s)) { 
     System.out.println(i); 
     break; 
    } 
}