Java 如何在 Joda Time 中获取短月份名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3025583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get short month names in Joda Time?
提问by Mr Morgan
Does anyone know if there's a method in Joda Time or Java itself which takes either an int or a String as an argument, e.g. 4 or "4" and gives the name of the month back in short format, i.e. JAN for January?
有谁知道在 Joda Time 或 Java 本身中是否有一种方法将 int 或 String 作为参数,例如 4 或“4”,并以短格式给出月份的名称,即一月的 JAN?
I suppose long month names can be truncated and converted to upper case.
我想可以将长月份名称截断并转换为大写。
采纳答案by puug
In response to Jon's answer, you can further simplify that by using Joda's direct access for datetime classes.
作为对 Jon 的回答的回应,您可以通过使用 Joda 对日期时间类的直接访问来进一步简化它。
String month = date.toString("MMM");
回答by Jon Skeet
I believe "MMM" will give the month name in Joda... but you'd need to build up an appropriate formatter first. Here's some sample code which prints "Apr" on my box. (You can specify the relevant locale of course.)
我相信“MMM”会在 Joda 中给出月份名称......但你需要先建立一个合适的格式化程序。这是一些示例代码,它在我的盒子上打印“Apr”。(当然,您可以指定相关的语言环境。)
import org.joda.time.*;
import org.joda.time.format.*;
public class Test
{
public static void main(String[] args)
{
// Year and day will be ignored
LocalDate date = new LocalDate(2010, 4, 1);
DateTimeFormatter formatter = DateTimeFormat.forPattern("MMM");
String month = formatter.print(date);
System.out.println(month);
}
}
回答by Powerlord
My last answer about using java.util.Calendar
for this was a little more complicated than it needed to be. Here's a simpler version, although it still requires Java 6 or newer.
我关于java.util.Calendar
为此使用的最后一个答案比它需要的要复杂一些。这是一个更简单的版本,尽管它仍然需要 Java 6 或更新版本。
import java.util.Calendar;
import java.util.Locale;
public class Test
{
public static void main(String[] args)
{
// Sample usage.
// Should be "Apr" in English languages
String month = getMonthNameShort(4);
System.out.println(month);
}
/**
* @param month Month number
* @return The short month name
*/
public static String getMonthNameShort(int month)
{
Calendar cal = Calendar.getInstance();
// Calendar numbers months from 0
cal.set(Calendar.MONTH, month - 1);
return cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());
}
}
回答by user3461390
LocalDateTime fecha_sistema = LocalDateTime.now();
// return month value betwen 1 to 12
int month = fecha_sistema.getMonthValue();
// return month name
String mes = fecha_sistema.getMonth().name();
System.out.println("Month" + mes + "/ " + month);