Reputation: 133
I have tried the code below, but it's not working.
Please explain why it's not working.
public static void main(String[] args) {
String ti = "11:30 PM, Sun 07 Oct 2018";
String sformat = "h:m a, E dd M yyyy";
String cformat = "hh:mm a";
String d = dateFormater(ti, cformat, sformat);
System.out.println(d);
}
public static String dateFormater(String dateFromJSON,
String expectedFormat, String oldFormat) {
SimpleDateFormat dateFormat = new SimpleDateFormat(oldFormat);
Date date = null;
String convertedDate = null;
try {
date = dateFormat.parse(dateFromJSON);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(expectedFormat);
convertedDate = simpleDateFormat.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return convertedDate;
}
Upvotes: 1
Views: 210
Reputation: 10083
Your date format is incorrect. Please use the format below.
String sformat= "hh:mm a, EEE dd MMM yyyy";
Upvotes: 1
Reputation: 54168
Your pattern needs
MMM
because the month is in short litteral format (M
only is for month number and MMMM
is for long litteral format)
String sformat = "h:m a, E dd MMM yyyy";
And you should consider using new time
API : java.time
as it's easier to use and don't need extra mandatory try/catch
:
public static String dateFormater(String dateFromJSON, String expectedFormat, String oldFormat) {
LocalDateTime date = LocalDateTime.parse(dateFromJSON, DateTimeFormatter.ofPattern(oldFormat, Locale.ENGLISH));
String newStr = date.format(DateTimeFormatter.ofPattern(expectedFormat, Locale.ENGLISH));
return newStr;
}
or in a single-line :
public static String dateFormaterSh(String dateFromJSON, String expectedFormat, String oldFormat) {
return LocalDateTime.parse(dateFromJSON, DateTimeFormatter.ofPattern(oldFormat, Locale.ENGLISH))
.format(DateTimeFormatter.ofPattern(expectedFormat, Locale.ENGLISH));
}
Upvotes: 1