Do not contaminate the clean java.time
API with the legacy error-prone java.util
date-time API. You can do it as follows using the modern date-time API:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now.format(DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm", Locale.ENGLISH)));
System.out.println(now.format(DateTimeFormatter.ofPattern("EEE MMM dd uuuu", Locale.ENGLISH)));
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu", Locale.ENGLISH);
ZonedDateTime givenDateTime = ZonedDateTime.parse("Thu Nov 05 00:00:00 CET 2020", dtfInput);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("EEE MMM dd z uuuu", Locale.ENGLISH);
System.out.println(givenDateTime.format(dtfOutput));
System.out.println(ZonedDateTime.now(ZoneId.of("Europe/Paris")).format(dtfOutput));
}
}
Output:
04-Nov-2020 17:13
Wed Nov 04 2020
Thu Nov 05 CET 2020
Wed Nov 04 CET 2020
Learn more about the modern date-time API at Trail: Date Time.
Using the legacy API:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
Date now = new Date();
System.out.println(new SimpleDateFormat("dd-MMM-yyyy HH:mm", Locale.ENGLISH).format(now));
System.out.println(new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH).format(now));
SimpleDateFormat sdfInput = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
Date givenDateTime = sdfInput.parse("Thu Nov 05 00:00:00 CET 2020");
SimpleDateFormat sdfOutput = new SimpleDateFormat("EEE MMM dd z yyyy", Locale.ENGLISH);
sdfOutput.setTimeZone(TimeZone.getTimeZone("CET"));
System.out.println(sdfOutput.format(givenDateTime));
System.out.println(sdfOutput.format(now));
}
}
Output:
04-Nov-2020 17:13
Wed Nov 04 2020
Thu Nov 05 CET 2020
Wed Nov 04 CET 2020