Is there a oneliner to get the name of the month when we know:
int monthNumber = calendar.get(Calendar.MONTH)
Or what is the easiest way?
You can achieve it using SimpleDateFormat, which is meant to format date and times:
Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));
String getMonthForInt(int num) {
String month = "wrong";
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
if (num >= 0 && num <= 11) {
month = months[num];
}
return month;
}
As simple as this
mCalendar = Calendar.getInstance();
String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
This is the solution I came up with for a class project:
public static String theMonth(int month){
String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
return monthNames[month];
}
The number you pass in comes from a Calendar.MONTH call.
If you have multi-language interface, you can use getDisplayName to display the name of month with control of displaying language.
Here is an example of displaying the month name in English, French, Arabic and Arabic in specific country like "Syria":
Calendar c = Calendar.getInstance();
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH ) );
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.FRANCE ) );
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, new Locale("ar") ) );
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, new Locale("ar", "SY") ) );
System.out.println(c.getTime().toString());
The result is:
January
janvier
يناير
كانون الثاني
Sat Jan 17 19:31:30 EET 2015
SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );
For some languages (e.g. Russian) this is the only correct way to get the stand-alone month names.
This is what you get, if you use getDisplayName from the Calendar or DateFormatSymbols for January:
января (which is correct for a complete date string: "10 января, 2014")
but in case of a stand-alone month name you would expect:
январь
Joda-Time
How about using Joda-Time. It's a far better date-time API to work with (And January means january here. It's not like Calendar, which uses 0-based index for months).
You can use AbstractDateTime#toString( pattern ) method to format the date in specified format:
DateTime date = DateTime.now();
String month = date.toString("MMM");
Month Name From Number
If you want month name for a particular month number, you can do it like this:
int month = 3;
String monthName = DateTime.now().withMonthOfYear(month).toString("MMM");
Localize
The above approach uses your JVM’s current default Locale for the language of the month name. You want to specify a Locale object instead.
String month = date.toString( "MMM", Locale.CANADA_FRENCH );
Month::getDisplayName
Since Java 8, use the Month enum. The getDisplayName method automatically localizes the name of the month.
Pass:
A TextStyle to determine how long or how abbreviated.
A Locale to specify the human language used in translation, and the cultural norms used for abbreviation, punctuation, etc.
Example:
public static String getMonthStandaloneName(Month month) {
return month.getDisplayName(
TextStyle.FULL_STANDALONE,
Locale.getDefault()
);
}
It might be an old question, but as a one liner to get the name of the month when we know the indices, I used
String month = new DateFormatSymbols().getMonths()[monthNumber - 1];
or for short names
String month = new DateFormatSymbols().getShortMonths()[monthNumber - 1];
Please be aware that your monthNumber starts counting from 1 while any of the methods above returns an array so you need to start counting from 0.
This code has language support.
I had used them in Android App.
String[] mons = new DateFormatSymbols().getShortMonths();//Jan,Feb,Mar,...
String[] months = new DateFormatSymbols().getMonths();//January,Februaty,March,...
I found this much easier(https://docs.oracle.com/javase/tutorial/datetime/iso/enum.html)
private void getCalendarMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Month month = Month.of(calendar.get(Calendar.MONTH));
Locale locale = Locale.getDefault();
System.out.println(month.getDisplayName(TextStyle.FULL, locale));
System.out.println(month.getDisplayName(TextStyle.NARROW, locale));
System.out.println(month.getDisplayName(TextStyle.SHORT, locale));
}
This works for me:
String getMonthName(int monthNumber) {
String[] months = new DateFormatSymbols().getMonths();
int n = monthNumber-1;
return (n >= 0 && n <= 11) ? months[n] : "wrong number";
}
To returns "September" with one line:
String month = getMonthName(9);
Calender cal = Calendar.getInstance(Locale.ENGLISH)
String[] mons = new DateFormatSymbols(Locale.ENGLISH).getShortMonths();
int m = cal.get(Calendar.MONTH);
String mName = mons[m];
Easiest Way
import java.text.DateFormatSymbols;
int month = 3; // March
System.out.println(new DateFormatSymbols().getMonths()[month-1]);
You can get it one line like this:
String monthName = new DataFormatSymbols.getMonths()[cal.get(Calendar.MONTH)]
One way:
We have Month API in Java (java.time.Month). We can get by using Month.of(month);
Here, the Month are indexed as numbers so either you can provide by Month.JANUARY or provide an index in the above API such as 1, 2, 3, 4.
Second way:
ZonedDateTime.now().getMonth();
This is available in java.time.ZonedDateTime.
It returns English name of the month.
04 returns APRIL and so on.
String englishMonth (int month){
return Month.of(month);
}
import java.text.SimpleDateFormat;
import java.util.Calendar;
Calendar cal = Calendar.getInstance();
String currentdate=new SimpleDateFormat("dd-MMM").format(cal.getTime());
I created a Kotlin extension based on responses in this topic and using the DateFormatSymbols answers you get a localized response.
fun Date.toCalendar(): Calendar {
val calendar = Calendar.getInstance()
calendar.time = this
return calendar
}
fun Date.getMonthName(): String {
val month = toCalendar()[Calendar.MONTH]
val dfs = DateFormatSymbols()
val months = dfs.months
return months[month]
}
DateFormat date = new SimpleDateFormat("dd/MMM/yyyy");
Date date1 = new Date();
System.out.println(date.format(date1));
For full name of month:
val calendar = Calendar.getInstance()
calendar.timeInMillis = date
return calendar.getDisplayName(Calendar.MONTH, Calendar.Long, Locale.ENGLISH)!!.toString()
And for short name of month:
val calendar = Calendar.getInstance()
calendar.timeInMillis = date
return calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.ENGLISH)!!.toString()
from the SimpleDateFormat java doc:
* <td><code>"yyyyy.MMMMM.dd GGG hh:mm aaa"</code>
* <td><code>02001.July.04 AD 12:08 PM</code>
* <td><code>"EEE, d MMM yyyy HH:mm:ss Z"</code>
* <td><code>Wed, 4 Jul 2001 12:08:56 -0700</code>
Related
How can the year in the output add up according to the month's summation?
int sewa = 10
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
String cyear = Integer.toString(year);
int mont = (now.get(Calendar.MONTH) + 1);
String cmont = Integer.toString(mont);
int day = (now.get(Calendar.DATE) );
String cday = Integer.toString(day);
String date = cyear +"/"+cmont+"/"+cday;
Calendar ex = Calendar.getInstance();
int exyear = ex.get(Calendar.YEAR);
String excyear = Integer.toString(exyear);
ex.add(Calendar.MONTH,+sewa);
int exmont = (ex.get(Calendar.MONTH) + 1);
String excmont = Integer.toString(exmont);
int exday = (ex.get(Calendar.DATE) );
String excday = Integer.toString(exday);
String exdate = excyear +"/"+excmont+"/"+excday;
System.out.println(date);
System.out.println("+++++");
System.out.println(exdate);
now : 2018/3/25
+++++ after:2018/1/25
how ouput :2019/1/25
If you are using Java 8 or newer version, please use LocalDate instead of Calendar class. It's very easy to add days, months and years using methods plusDays(), plusMonths() and plusYears(). It's that simple:
LocalDate today = LocalDate.now();
today.plusDays(20);
today.plusMonths(1);
today.plusYears(5);
LocalDate and LocalDateTime were introduced with JSR-310 as much simpler, straightforward and easy to use replacement of Date and Calendar.
However, if you use older version of java, or need to use Date and Calendar for some other reason, you can increase the number of years the same way you did with the months, using
ex.add(Calendar.YEAR, 5);
You capture the year to a variable ...
int exyear = ex.get(Calendar.YEAR);
String excyear = Integer.toString(exyear);
... right before you add 10 months to the calendar ...
ex.add(Calendar.MONTH,+sewa);
... which causes the excyear remains not updated.
To solve it, give the statements a correct order (Get Calendar -> add the months -> get Strings -> print). Or better using SimpleDateFormat:
Calendar ex = Calendar.getInstance();
ex.add(Calendar.MONTH, sewa);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String exdate = sdf.format(ex.getTime());
System.out.println(exdate);
Prints out:
2019/01/25
I using DatePicker for to choose the date.Everything going good. But the problem is to Format the date.
// display current date
public void setCurrentDateOnView() {
tvDisplayDate = (TextView) findViewById(R.id.tvDate);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
tvDisplayDate.setText(new StringBuilder().append(year).append("-").append(month + 1).append("-").append(day).append(" "));
// Month is 0 based, just add 1
}
As per Code i am getting the OUTPUT: 2016-8-22
but
My expected output is 2016-08-22(I want month like this 08)
Thank you,
regards,
Karthi.
Use SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
tvDisplayDate.setText(sdf.format(c.getTime()));
For more Information about SimpleDateFormat see the official documentation
Try this it may be help to you
public static String updateDate(int day, int month, int year) {
String monthformatted = "";
if (month < 10)
monthformatted = "0" + month;
else
monthformatted = String.valueOf(month);
String dayformatted = "";
if (day < 10)
dayformatted = "0" + day;
else
dayformatted = String.valueOf(day);
// Append in a StringBuilder
String aDate = new StringBuilder().append(year).append('-')
.append(monthformatted).append("-").append(dayformatted).toString();
return aDate;
}
and called this method like
tvDisplayDate.setText(updateDate(day,month+1,year));
private SimpleDateFormat dateFormatter;
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
tvDisplayDate.setText(dateFormatter.format(newDate.getTime()));
Add this and You will succeed
// display current date
public void setCurrentDateOnView() {
tvDisplayDate = (TextView) findViewById(R.id.tvDate);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
String formattedDate = String.format(Locale.ENGLISH, "%d-%02d-%02d", year, (month + 1), day);
tvDisplayDate.setText(formattedDate);
}
Use SimpleDateFormat class.. There are a lot of ways to do it..
something like this..
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MM-yy");
// you can add any format..
Date date = sdfSource.parse(strDate);
String format will help you ...
String month=String.format("%02d",cal.get(Calendar.MONTH));
String day=String.format("%02d",cal.get(Calendar.DAY_OF_MONTH)+1);
String year=String.format("%02d",cal.get(Calendar.YEAR));
String full_date = month+ "-" + day + "-" +year ;
You can append zero using String formation
String.format("%02d", month);
// display current date
public void setCurrentDateOnView() {
tvDisplayDate = (TextView) findViewById(R.id.tvDate);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
tvDisplayDate.setText(new StringBuilder().append(year).append("-").append(String.format("%02d", month+ 1)).append("-").append(day).append(" "));
// Month is 0 based, just add 1
}
Hope this will help
use the below code to set date as you want
tvDisplayDate.setText(String.format("%04d-%02d-%0d,year,month,date);
tl;dr
LocalDate.now( ZoneId.of( "America/Montreal" ) ).toString()
java.time
You are using troublesome old legacy classes now supplanted by the java.time classes.
Be sure to specify a time zone. If omitted your JVM’s current zone is implicitly applied. That default varies, even during runtime. Better to be specific.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Or specify the year, month, day-of-month.
LocalDate ld = LocalDate.of( 2016 , 1 , 2 );
The month number is sane, 1-12 for January-December. Alternatively you can pass a Month enum object instead of mere integer.
LocalDate ld = LocalDate.of( 2016 , Month.JANUARY , 2 );
Generate String
The java.time classes use standard ISO formats when parsing and generating strings. That happens to be your desired format.
String output = today.toString();
Same format can be parsed.
LocalDate ld = LocalDate.parse( "2016-01-02" );
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy",Locale.US);
tvDisplayDate.setText(simpleDateFormat.format(new Date().getTime()));
How do I create a function which take current date and return month name?
I have only date its not current date it can be any date like 2013/4/12 or 23/8/8.
Like String monthName("2013/9/11");
when call this function return the month name.
This should be fine.
It depends on the format of date.
If you try with February 1, 2011
it would work, just change this string "MMMM d, yyyy" according to your needs.
Check this for all format patterns.
And also, months are 0 based, so if you want January to be 1, just return month + 1
private static int getMonth(String date) throws ParseException{
Date d = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int month = cal.get(Calendar.MONTH);
return month + 1;
}
If you want month name try this
private static String getMonth(String date) throws ParseException{
Date d = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
String monthName = new SimpleDateFormat("MMMM").format(cal.getTime());
return monthName;
}
As I said, check web page I posted for all format patterns. If you want only 3 characters of month, use "MMM" instead of "MMMM"
java.time
I am contributing the modern answer.
System.out.println(LocalDate.of(2013, Month.SEPTEMBER, 11) // Define the date
.getMonth() // Get the month
.getDisplayName( // Get the month name
TextStyle.FULL_STANDALONE, // No abbreviation
Locale.ENGLISH)); // In which language?
Output is:
September
Use LocalDate from java.time, the modern Java date and time API, for a date.
Use LocalDate.getMonth() and Month.getDisplayName() to get the month name.
Avoid Date, Calendar and SimpleDateFormat used in the old answers from 2013. Those classes are poorly designed, troublesome and long outdated. The modern API is so much nicer to work with. Also avoid switch/case for this purpose since the month names are already built in, and using the library methods gives you clearer, terser and less error-prone code.
Use LocalDate
LocalDate today = LocalDate.now(ZoneId.systemDefault());
LocalDate aDate = LocalDate.of(2013, Month.SEPTEMBER, 11); // 2013/9/11
LocalDate anotherDate = LocalDate.of(2023, 8, 8); // 23/8/8
If you are getting the date as string input, parse the string using a DateTimeFormatter:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("u/M/d");
String stringInput = "2013/4/12";
LocalDate date = LocalDate.parse(stringInput, dateFormatter);
System.out.println(date);
2013-04-12
Use LocalDate.getMonth() and Month.getDisplayName()
To get the month name you first need to decide in which language you want the month name. I am taking English as an example and still using date from the previous snippet:
String monthName = date.getMonth()
.getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH);
System.out.println(monthName);
April
Java knows the month names in a wealth of languages. If you want the month name in the user’s language, pass Locale.getDefault() as the second argument to getDisplayName().
Link
Oracle tutorial: Date Time explaining how to use java.time.
Use this code -
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int month = calendar.get(Calendar.MONTH);
So now you have month number, you can use switch case to get name for that month.
If your date is in string format use this-
Date date = new SimpleDateFormat("yyyy-MM-dd").format(d)
Simple solution to get current month by name:
SimpleDateFormat formatterMonth = new SimpleDateFormat("MMMM");
String currentMonth = formatterMonth.format(new Date(System.currentTimeMillis()));
Function to get any month by name using format 2013/9/11: (not tested)
private String monthName(String dateToCheck){
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
date = formatter.parse(dateToCheck);
SimpleDateFormat formatterMonth = new SimpleDateFormat("MMMM");
return formatterMonth.format(new Date(date.getTime()));
}
I am using a function like this:
public String getDate(String startDate) throws ParseException {
#SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = null;
try {
d = sdf.parse(startDate);
sdf.applyPattern("MMMM dd, YYYY"); //this gives output as=> "Month date, year"
} catch (Exception e) {
Log.d("Exception", e.getLocalizedMessage());
}
return sdf.format(d);
}
You can obtain the "number" of the month as described in the other answer and then you could simply use a switch to obtain a name.
Example:
switch(month) {
case 0:
your name is January
break;
...
}
P.S. I think months are zero-based but I'm not 100% sure...
I can't resolve this question.
I wrote this code:
public static String getMonthName(int year, int month, int day){
Locale locale = Locale.getDefault();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM",locale);
Date date = new Date();
date.setDate(day);
date.setMonth(month);
date.setYear(year);
return sdf.format(date);
}
It works very well but when month = 1 (that is February), month name is March and not February! Why?
This code works very well for all other days and months...
There is another way to get translated month name?
Please help me....
Depending on how you call your function (eg using current day as the 29 of Feb which doesn't exist in 2013), you may make the month being incremented automatically.
I'd suggest the use of this function which avoids the problem :
public static String getMonthName(int month){
Locale locale = Locale.getDefault();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM",locale);
Date date = new Date();
date.setDate(1);
date.setMonth(month);
date.setYear(2012);
return sdf.format(date);
}
This is because the months start from zero index, So you should use this logic
if(day >0)
{
day =day -1;
}
I have a problem to sort date because of the format of these dates.
I obtain the date :
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
And I build a String with these values.
dateRappDB = (new StringBuilder()
.append(mYear).append(".")
.append(mMonth + 1).append(".")
.append(mDay).append(" ")).toString();
The problem is that if the month is for example February, mMonth value is 2. So dates with months like October (10) comes before in my list.
What I need is that month and day are formated like MM and dd. But I don't know how to do it in my case.
EDIT :
I solved the problem by using a DateFormat like said above.
I replaced this :
dateRappDB = (new StringBuilder()
.append(mYear).append(".")
.append(mMonth + 1).append(".")
.append(mDay).append(" ")).toString();
By this :
Date date = new Date(mYear - 1900, mMonth, mDay);
dateFacDB = DateFormat.format("yyyy.MM.dd", date).toString();
And it works.
Thanks to all of you for your help :)
here is a simple way to convert Date to String :
SimpleDateFormat simpleDate = new SimpleDateFormat("dd/MM/yyyy");
String strDt = simpleDate.format(dt);
Calendar calendar = Calendar.getInstance();
Date now = calendar.getTime();
String timestamp = simpleDateFormat.format(now);
These might come in handy
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ");
this format is equal to --> "2016-01-01T09:30:00.000000+01:00"
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
this format is equal to --> "2016-06-01T09:30:00+01:00"
here is the example for date format
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
System.out.println("format 1 " + sdf.format(date));
sdf.applyPattern("E MMM dd yyyy");
System.out.println("format 2 " + sdf.format(date));
You need to sort dates, not strings. Also, have you heared about DateFormat? It makes all that appends for you.
If I understand your issue, you create a list of dates and since they're strings, they get arranged in a dictionary-order number-wise, which means you get october before february (10 before 2).
If I were you, I would store my results in a container where I control the insertion point (like an array list) or where I can control the sorting algorithm.