I have a date in String format as Jun/2014. I want to convert it to a date. It is ok to have any day for this date.
How to achieve this? I tried following code but it did not work.
String fromdate="Jun/2014";
SimpleDateFormat format = new SimpleDateFormat("mm/yyyy");
String date = format.format(fromdate);
You should try
String fromdate = "Jun/2014";
SimpleDateFormat format = new SimpleDateFormat("MMM/yyyy");
Date date = null;
try {
date = format.parse(fromdate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(date);
Your result : Sun Jun 01 00:00:00 ECT 2014
The javadoc has pretty decent explanation on this. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
I am just pasting the example provided in the above link. As can be seen, it should be MMM for Jul
Date and Time Pattern Result
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3
String fromdate="Jun/2014";
SimpleDateFormat f = new SimpleDateFormat("MMM/yyyy");
try {
Date date = f.parse(fromdate);
String d = f.format(date);
System.out.println(d);
} catch (ParseException e) {
e.printStackTrace();
}
The classes used in the other answers (.Date, .Calendar, .SimpleDateFormat) are notoriously troublesome, flawed in both design and implementation. Avoid them. Instead use either Joda-Time or the java.time package new in Java 8.
Another problem with the classes used in the other answers: No way to represent a date-only without any time-of-day portion. Both Joda-Time and java.time offer a LocalDate
class for that purpose.
Here is example code in Joda-Time 2.3.
String input = "Jun/2014";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MMM/yyyy" );
LocalDate localDate = formatter.parseLocalDate( input ); // Assumes the first of the month.
Dump to console.
System.out.println( "input: " + input );
System.out.println( "localDate: " + localDate );
When run.
input: Jun/2014
localDate: 2014-06-01
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.