How to convert a string to date..
String sampledate="2008-04"; Expected :
I want to convert it to "Apr-08" Month as mmm and Last two digits of year.
I tried using simpledatefromatter.parse but dint work as expected , can anyone suggest a way in java .
CodePudding user response:
All you need is available in the SimpleDateFormat class.
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMM-yy");
String s = "2008-04";
Date d = sdf1.parse(s);
String s2 = sdf2.format(d);
System.out.println("raw: " s);
System.out.println("parsed: " d);
System.out.println("formatted: " s2);
}
The output will be:
raw: 2008-04
parsed: Tue Apr 01 00:00:00 CEST 2008
formatted: Apr-08
CodePudding user response:
Using Java 8 API:
YearMonth yearMonth = YearMonth.parse("2008-04");
String formatted = yearMonth.format(DateTimeFormatter.ofPattern("MMM-uu", Locale.ROOT));
System.out.println(formatted);