Change date format in a Java string

Use LocalDateTime#parse() (or ZonedDateTime#parse() if the string happens to contain a time zone part) to parse a String in a certain pattern into a LocalDateTime. String oldstring = “2011-01-18 00:00:00.0”; LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss.S”)); Use LocalDateTime#format() (or ZonedDateTime#format()) to format a LocalDateTime into a String in a certain pattern. String newstring = datetime.format(DateTimeFormatter.ofPattern(“yyyy-MM-dd”)); System.out.println(newstring); // 2011-01-18 Or, when you’re not on Java 8 yet, use SimpleDateFormat#parse() to parse a String in … Read more

Convert java.util.Date to String

Convert a Date to a String using DateFormat#format method: String pattern = “MM/dd/yyyy HH:mm:ss”; // Create an instance of SimpleDateFormat used for formatting // the string representation of date according to the chosen pattern DateFormat df = new SimpleDateFormat(pattern); // Get the today date using Calendar object. Date today = Calendar.getInstance().getTime(); // Using DateFormat format method we can create a string … Read more