Parsing a String to Date Format in Java Defaults Date to 1 and Month to January

Java string to date conversion

That's the hard way, and those java.util.Date setter methods have been deprecated since Java 1.1 (1997). Moreover, the whole java.util.Date class was de-facto deprecated (discommended) since introduction of java.time API in Java 8 (2014).

Simply format the date using DateTimeFormatter with a pattern matching the input string (the tutorial is available here).

In your specific case of "January 2, 2010" as the input string:

  1. "January" is the full text month, so use the MMMM pattern for it
  2. "2" is the short day-of-month, so use the d pattern for it.
  3. "2010" is the 4-digit year, so use the yyyy pattern for it.
String string = "January 2, 2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2010-01-02

Note: if your format pattern happens to contain the time part as well, then use LocalDateTime#parse(text, formatter) instead of LocalDate#parse(text, formatter). And, if your format pattern happens to contain the time zone as well, then use ZonedDateTime#parse(text, formatter) instead.

Here's an extract of relevance from the javadoc, listing all available format patterns:

































































































































































































SymbolMeaningPresentationExamples
GeratextAD; Anno Domini; A
uyearyear2004; 04
yyear-of-erayear2004; 04
Dday-of-yearnumber189
M/Lmonth-of-yearnumber/text7; 07; Jul; July; J
dday-of-monthnumber10
Q/qquarter-of-yearnumber/text3; 03; Q3; 3rd quarter
Yweek-based-yearyear1996; 96
wweek-of-week-based-yearnumber27
Wweek-of-monthnumber4
Eday-of-weektextTue; Tuesday; T
e/clocalized day-of-weeknumber/text2; 02; Tue; Tuesday; T
Fweek-of-monthnumber3
aam-pm-of-daytextPM
hclock-hour-of-am-pm (1-12)number12
Khour-of-am-pm (0-11)number0
kclock-hour-of-am-pm (1-24)number0
Hhour-of-day (0-23)number0
mminute-of-hournumber30
ssecond-of-minutenumber55
Sfraction-of-secondfraction978
Amilli-of-daynumber1234
nnano-of-secondnumber987654321
Nnano-of-daynumber1234000000
Vtime-zone IDzone-idAmerica/Los_Angeles; Z; -08:30
ztime-zone namezone-namePacific Standard Time; PST
Olocalized zone-offsetoffset-OGMT+8; GMT+08:00; UTC-08:00;
Xzone-offset 'Z' for zerooffset-XZ; -08; -0830; -08:30; -083015; -08:30:15;
xzone-offsetoffset-x+0000; -08; -0830; -08:30; -083015; -08:30:15;
Zzone-offsetoffset-Z+0000; -0800; -08:00;

Java: Convert String Date to Month Name Year (MMM yyyy)

Your format must match your input

for 2016-03-20

the format should be (just use a second SimpleDateFormat object)

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


Full answer

SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

String actualDate = "2016-03-20";

Date date = sdf.parse(actualDate);

String month_name = month_date.format(date);
System.out.println("Month :" + month_name); //Mar 2016

Using java.time java-8

String actualDate = "2016-03-20";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("MMM yyyy", Locale.ENGLISH);
DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("MMMM yyyy", Locale.ENGLISH);
LocalDate ld = LocalDate.parse(actualDate, dtf);
String month_name = dtf2.format(ld);
System.out.println(month_name); // Mar 2016
String fullMonthAndYear = dtf3.format(ld);
System.out.println(fullMonthAndYear); // March 2016

Parse String to Date with Different Format in Java

Take a look at SimpleDateFormat. The code goes something like this:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

try {

String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
e.printStackTrace();
}

Getting last day of the month in a given string date

Java 8 and above.

By using convertedDate.getMonth().length(convertedDate.isLeapYear()) where convertedDate is an instance of LocalDate.

String date = "1/13/2012";
LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));
convertedDate = convertedDate.withDayOfMonth(
convertedDate.getMonth().length(convertedDate.isLeapYear()));

Java 7 and below.

By using getActualMaximum method of java.util.Calendar:

String date = "1/13/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(convertedDate);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_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");

Converting ISO 8601-compliant String to java.util.Date

Unfortunately, the time zone formats available to SimpleDateFormat (Java 6 and earlier) are not ISO 8601 compliant. SimpleDateFormat understands time zone strings like "GMT+01:00" or "+0100", the latter according to RFC # 822.

Even if Java 7 added support for time zone descriptors according to ISO 8601, SimpleDateFormat is still not able to properly parse a complete date string, as it has no support for optional parts.

Reformatting your input string using regexp is certainly one possibility, but the replacement rules are not as simple as in your question:

  • Some time zones are not full hours off UTC, so the string does not necessarily end with ":00".
  • ISO8601 allows only the number of hours to be included in the time zone, so "+01" is equivalent to "+01:00"
  • ISO8601 allows the usage of "Z" to indicate UTC instead of "+00:00".

The easier solution is possibly to use the data type converter in JAXB, since JAXB must be able to parse ISO8601 date string according to the XML Schema specification. javax.xml.bind.DatatypeConverter.parseDateTime("2010-01-01T12:00:00Z") will give you a Calendar object and you can simply use getTime() on it, if you need a Date object.

You could probably use Joda-Time as well, but I don't know why you should bother with that (Update 2022; maybe because the entire javax.xml.bind section is missing from Android's javax.xml package).



Related Topics



Leave a reply



Submit