How to get short month names in Joda Time?
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?
I suppose long month names can be truncated and converted to upper case.
In response to Jon's answer, you can further simplify that by using Joda's direct access for datetime classes.
String month = date.toString("MMM");
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.)
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);
}
}
We can do as following:
DateTime dt = new DateTime(); // current time
String monthStr = dt.month().getAsShortText(); // gets the month name
Also you can use getAsText()
method for long month name.
Reference
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);
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.
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());
}
}
精彩评论