【问题标题】:How can I convert an Integer to month name in Groovy?如何在 Groovy 中将整数转换为月份名称?
【发布时间】:2013-09-18 09:13:08
【问题描述】:

我得到一个整数,我需要在当前语言环境中转换为月份名称:

语言环境 en-us 示例: 1 -> 一月 2 -> 二月

我在 gremlin 中的代码示例:

.....groupBy{[it[3], it[2].getMonth()]}{it[1]}{it.sum()}.cap().scatter().transform{[Name:it.key,Tx:it.value]}

我在这里得到:

==>{Name=[ABC, 7], Tx=1750.0}

我想要名称格式的月份整数。

我试过了,

it[2].getMonth().toString() and also as cal.get(Calendar.MONTH) etc。但没有成功。

【问题讨论】:

  • Replace("Thanks", "Acceptance").... :-)

标签: groovy gremlin


【解决方案1】:

要将月份整数转换为字符串,您可以:

String month = new java.text.DateFormatSymbols().months[ 4 ]

assert month == 'May'

【讨论】:

  • new java.text.DateFormatSymbols().months[it[2].getMonth()]... 它正在工作。谢谢。
  • 如何以本月年份格式显示以上内容,例如:7 月 12 日、8 月 13 日等?
  • 我试过了,但又以整数方式显示月份。 {new Date(it.getProperty("date")).format('MM yy')} 它显示为 02 12 , 03 12 ...month name 再次返回整数形式。 :(
  • {new Date(it.getProperty("date")).format('MMM yy')} .. 对不起我的错。谢谢 。 :)
【解决方案2】:

考虑这三种方法,希望对您有所帮助。

1)您可以通过将月份指定为整数来执行以下操作

import java.text.DateFormatSymbols;
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month-1];
}

2)您可以通过给出日期来执行以下操作

SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );

3)使用 SimpleDateFormat。

import java.text.SimpleDateFormat;

public String formatMonth(String month) {
SimpleDateFormat monthParse = new SimpleDateFormat("MM");
SimpleDateFormat monthDisplay = new SimpleDateFormat("MMMM");
return monthDisplay.format(monthParse.parse(month));
}
formatMonth("2"); //Result: February

【讨论】:

  • 在 Groovy 中,您的选项 #3 可以简化为 String formatMonth( int month ) { Date.parse( 'MM', "$month" ).format( 'MMMM' ) }
  • 感谢这些差异。技术。
猜你喜欢
  • 2013-03-08
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多