Java Simpledateformat Always Returning January for Month

Java SimpleDateFormat always returning January for Month

Change the pattern string from "yyyy/MM/DD" to "yyyy/MM/dd"

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

Java parse date string returns wrong month

This is due to the format you used as "yyyy-MM-DD". The parser will parse in the sequence way:

  • Your input value is "2018-03-08"
  • yyyy - will bring to the year 2018
  • MM - will bring to the month MARCH

But what is DD? It's the number of the days from the beginning of the year.
So here it moved back to 8th day on this year (2018) which means January 8th.

That's why you are seeing January instead of March.

Why is SimpleDateFormat parsing Date with wrong Month and Day?

DD is wrong. D is day of year. Sixth day of year is January 6.

You should use dd.

Docs: SimpleDateFormat

Java SimpleDateFormat not detecting month

You are using the wrong date format string: DD (day in year) instead of dd (day in month). Change both SimpleDateFormat instance to use dd:

DateFormat inputFormat = new SimpleDateFormat("yyyyMMddhhmmss");
DateFormat outputFormat = new SimpleDateFormat("YYYY-MM-dd'T'hh:mm:ss'Z'");

Therefore you are getting the wrong result.

DatePicker always gives January in returned date

You are passing the day of month as the DAY_OF_YEAR, so it is overriding the month you set. But I agree with the above comment. Use LocalDate instead of Calendar.

Calendar, Date, TimeZone, and other java.util date-time related classes are considered obsolete. Unfortunately, DatePicker predates availability of the java.time classes like LocalDate, so it may be easiest to use Calendar if you're just converting to UTC millis and back.

SimpleDateFormat returning incorrect day on given date

You should be using SimpleDateFormat("dd-MM-yyyy").

DD is for day in year, like there are 365 days in a year.

Simpledateformat - Why Calendar.MONTH wrongly generate previous month value(ie Dec-2015) for January'16?

There are a couple of issues with the code.

1) You should use add calendar.add(Calendar.MONTH, -1); to subtract the month.

2) Interestingly after that too it would print the output as month_name : Dec-2016 this is because your SimpleDateFormat has an issue, i.e. you have mentioned the year as capital Y which is Week year changing it to y will do the job.

You can refer to the SimpleDateFormat documentation here.

The modified code will be:

public static void main (String[] args) throws java.lang.Exception
{
SimpleDateFormat month_date = new SimpleDateFormat("MMM-yyyy");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);

String month_name = month_date.format(calendar.getTime());
System.out.println("month_name : "+month_name);
}


Related Topics



Leave a reply



Submit