java.time
DateTimeFormatter newFormatter
= DateTimeFormatter.ofPattern("dd MMM uuuu'T'HH:mm", Locale.ENGLISH);
String date1 = "2018-07-14T22:11";
LocalDateTime dateTime = LocalDateTime.parse(date1);
String contactDate = dateTime.format(newFormatter);
System.out.println(contactDate);
(It’s pretty much what YCF_L already said in a comment.) Output:
14 Jul 2018T22:11
To get the month abbreviation in uppercase, like JUL: The straightforward and a bit hacky way is:
String contactDate = dateTime.format(newFormatter).toUpperCase(Locale.ENGLISH);
With this change the output is:
14 JUL 2018T22:11
It only works because the string doesn’t contain any lowercase letters that we want to stay lowercase. To make sure only the month (and nothing else) is converted to uppercase:
Map<Long, String> monthAbbreviations = Arrays.stream(Month.values())
.collect(Collectors.toMap(m -> Long.valueOf(m.getValue()),
m -> m.getDisplayName(TextStyle.SHORT, Locale.ENGLISH)
.toUpperCase(Locale.ENGLISH)));
DateTimeFormatter newFormatter = new DateTimeFormatterBuilder()
.appendPattern("dd ")
.appendText(ChronoField.MONTH_OF_YEAR, monthAbbreviations)
.appendPattern(" uuuu'T'HH:mm")
.toFormatter(Locale.ENGLISH);
Now we get the desired result without calling toUpperCase
on the entire result string.
If you need to subtract 5 days. I’m not sure you mean it, but you asked for July 9 as a result. Easy when you know how:
dateTime = dateTime.minusDays(5);
With this line inserted into my first snippet above I get:
09 Jul 2018T22:11
What went wrong in your code
First, new Date()
gives the current date and time and ignores the string you got with a future date. Second, your format pattern string contained only hours, not minutes. You need to use lowercase mm
for minutes as I do in my code.
I do however recommend that you avoid the long outdated and notoriously troublesome SimpleDateFormat
class. java.time
, the modern Java date and time API, is so much nicer to work with.
Link
Oracle tutorial: Date Time explaining how to use java.time
.