Android: Java SimpleDateFormat: Why February is March? - java

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;
}

Related

why use different date format makes different result in same date?

I try to use current date in date formats but when I use different date formats this makes different results..at first I used this code:
private String getTodayDateString() {
Calendar cal = Calendar.getInstance();
int month=cal.get(Calendar.MONTH);
return Integer.toString(month);
}
and this return me 5 for result for month.
but when I use this code:
private String getTodayDateString2() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
return dateFormat.format(cal.getTime());
}
function returns me 14/6/2016 and this means month is calculated 6 in this dateformat.why?where is the problem?
months in calender starts from 0
0 =january
11=december
if you see the source code of Calendar class you will find public final static int JANUARY = 0;
similarily for december public final static int DECEMBER = 11;
Check the source code here

how to get month name using current date as input in function

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...

How can I get Month Name from Calendar?

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>

Challenging Java/Groovy Date Manipulation

I have a bunch of dates formatted with the year and week, as follows:
2011-10
The week value is the week of the year(so 1-52). From this week value, I need to output something like the following:
Mar 7
Explicitly, I need the Month that the given week is in, and the date of the first Monday of that week. So in other words it is saying that the 10th week of the year is the week of March 7th.
I am using Groovy. What kind of date manipulation can I do to get this to work?
Here's a groovy solution:
use(groovy.time.TimeCategory) {
def (y, w) = "2011-10".tokenize("-")
w = ((w as int) + 1) as String
def d = Date.parse("yyyy-w", "$y-$w") + 1.day
println d.format("MMM dd")
}
Use a GregorianCalendar (or Joda, if you don't mind a dependency)
String date = "2011-10";
String[] parts = date.split("-");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, Integer.parseInt(parts[0]));
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(parts[1])+1);
DateFormat df = new SimpleDateFormat("MMM d");
System.out.println(df.format(cal.getTime()) + " (" + cal.getTime() + ")");
EDIT: Added +1 to week, since calendar uses zero-based week numbers
Date date = new SimpleDateFormat("yyyy-w", Locale.UK).parse("2011-10");
System.out.println(new SimpleDateFormat("MMM d").format(date));
The first line returns first day of the 10th week in British Locale (March 7th). When Locale is not enforced, the results are dependent on default JVM Locale.
Formats are explained here.
You can use SimpleDateFormat, just like in java. See groovyconsole.appspot.com/script/439001
java.text.DateFormat df = new java.text.SimpleDateFormat('yyyy-w', new Locale('yourlocale'))
Date date = df.parse('2011-10')
To add a week, simply use Date date = df.parse('2011-10')+7
You don't need to set the Locale if your default Locale is using Monday as the first day of week.

How to get previous date in java

I have a String Object in format yyyyMMdd.Is there a simple way to get a String with previous date in the same format?
Thanks
I would rewrite these answers a bit.
You can use
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
// Get a Date object from the date string
Date myDate = dateFormat.parse(dateString);
// this calculation may skip a day (Standard-to-Daylight switch)...
//oneDayBefore = new Date(myDate.getTime() - (24 * 3600000));
// if the Date->time xform always places the time as YYYYMMDD 00:00:00
// this will be safer.
oneDayBefore = new Date(myDate.getTime() - 2);
String result = dateFormat.format(oneDayBefore);
To get the same results as those that are being computed by using Calendar.
Here is how to do it without Joda Time:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static String previousDateString(String dateString)
throws ParseException {
// Create a date formatter using your format string
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
// Parse the given date string into a Date object.
// Note: This can throw a ParseException.
Date myDate = dateFormat.parse(dateString);
// Use the Calendar class to subtract one day
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -1);
// Use the date formatter to produce a formatted date string
Date previousDate = calendar.getTime();
String result = dateFormat.format(previousDate);
return result;
}
public static void main(String[] args) {
String dateString = "20100316";
try {
// This will print 20100315
System.out.println(previousDateString(dateString));
} catch (ParseException e) {
System.out.println("Invalid date string");
e.printStackTrace();
}
}
}
You can use:
Calendar cal = Calendar.getInstance();
//subtracting a day
cal.add(Calendar.DATE, -1);
SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
String result = s.format(new Date(cal.getTimeInMillis()));
It's much harder than it should be in Java without library support.
You can parse the given String into a Date object using an instance of the SimpleDateFormat class.
Then you can use Calendar's add() to subtract one day.
Then you can use SimpleDateFormat's format() to get the formatted date as a String.
The Joda Time library a much easier API.
This is an old question, and most existing answers pre-date Java 8. Hence, adding this answer for Java 8+ users.
Java 8 introduced new APIs for Date and Time to replace poorly designed, and difficult to use java.util.Date and java.util.Calendar classes.
To deal with dates without time zones, LocalDate class can be used.
String dateString = "20200301";
// BASIC_ISO_DATE is "YYYYMMDD"
// See below link to docs for details
LocalDate date = LocalDate.parse(dateString, DateTimeFormatter.BASIC_ISO_DATE);
// get date for previous day
LocalDate previousDate = date.minusDays(1);
System.out.println(previousDate.format(DateTimeFormatter.BASIC_ISO_DATE));
// prints 20200229
Docs:
DateTimeFormatter.BASIC_ISO_DATE
LocalDate
use SimpleDateFormat to parse the String to Date, then subtract one day. after that convert the date to String again.
HI,
I want to get 20 days previous, to current date,
Calendar cal = Calendar.getInstance();
Calendar xdate = (Calendar)cal.clone();
xdate.set(Calendar.DAY_OF_YEAR, - 20);
System.out.println(" Current Time "+ cal.getTime().toString());
System.out.println(" X Time "+ xdate.getTime().toString());
I had some UN Expected result, When i tried on Jan 11th,
Current Time Tue Jan 11 12:32:16 IST 2011
X Time Sat Dec 11 12:32:16 IST 2010
Calendar cal = Calendar.getInstance();
Calendar xdate = (Calendar)cal.clone();
xdate.set(Calendar.DAY_OF_YEAR,cal.getTime().getDate() - 20 );
System.out.println(" Current Time "+ cal.getTime().toString());
System.out.println(" X Time "+ xdate.getTime().toString());
This code solved my Problem.
If you are willing to use the 3rd-party utility, Joda-Time, here is some example code using Joda-Time 2.3 on Java 7. Takes just two lines.
String dateAsString = "20130101";
org.joda.time.LocalDate someDay = org.joda.time.LocalDate.parse(dateAsString, org.joda.time.format.DateTimeFormat.forPattern("yyyymmdd"));
org.joda.time.LocalDate dayBefore = someDay.minusDays(1);
See the results:
System.out.println("someDay: " + someDay );
System.out.println("dayBefore: " + dayBefore );
When run:
someDay: 2013-01-01
dayBefore: 2012-12-31
This code assumes you have no time zone. Lacking a time zone is rarely a good thing, but if that's your case, that code may work for you. If you do have a time zone, use a DateTime object instead of LocalDate.
About that example code and about Joda-Time…
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
you can create a generic method which takes
- Date (String) (current date or from date),
- Format (String) (your desired fromat) and
- Days (number of days before(-ve value) or after(+ve value))
as input and return your desired date in required format.
following method can resolve this problem.
public String getRequiredDate(String date , String format ,int days){
try{
final Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat(format).parse(date));
cal.add(Calendar.DATE, days);
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.format(cal.getTime());
}
catch(Exception ex){
logger.error(ex.getMessage(), ex);
}
return date;
}
}
In Java 8 we can use directly for this purpose
LocalDate todayDate = LocalDate.now();
By default it provide the format of 2021-06-07, with the help of formater we can change this also
LocalDate previousDate = todayDate.minusDays(5);
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.YEAR, -1);
Date dt2 = new Date(cal2.getTimeInMillis());
System.out.println(dt2);

Categories