I know this is common to ask but I've wondered why it didn't work when I tried to convert the DateTime to words So I have this format
Provided format
2022-05-18 22:30:00
Result/Convert to
May 18, 2022 10:30 PM
This is what I've tried but it returns me an error need help
java.lang.IllegalArgumentException: Cannot format given Object as a Date
Sample
String schedule = "2022-05-18 22:30:00";
String outputPattern = "dd-MMM-yyyy h:mm a";
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
String str = null;
str = outputFormat.format(schedule);
holder.aptDate.setText(str);
CodePudding user response:
You need to parse your input string to a date class, and then format the date in desired format.
public class Temp {
public static void main(String[] args) throws Exception {
String schedule = "2022-05-18 22:30:00";
String outputPattern = "MMM dd, yyyy h:mm a";
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(schedule, inputFormatter);
String output = DateTimeFormatter.ofPattern(outputPattern).format(dateTime);
System.out.println(output);
}
}
This example uses LocalDateTime, located in java.time
package, which contains the modern java date-time API.
CodePudding user response:
You cannot format String
to Date
. Convert the input to date first, then format.
Eg:
String inputPattern = "dd-MMM-yyyy h:mm a";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
Date d = inputFormat.parse(schedule);
Now you can format it into any pattern you want.
str = outputFormat.format(d.getTime());
If possible try to use java.time
for DateTime as util.date
is deprecated.