
LocalDateTime datetime = LocalDateTime.parse( input, oldPattern)

JAVA SETDATE CODE
If your pattern just contains a date then you can use a LocalDate class instead.Īnyway, here is to JDK 8 code example to change the date format in Java String:ĭateTimeFormatter oldPattern = DateTimeFormatterĭateTimeFormatter newPattern = DateTimeFormatter.ofPattern( "yyyy-MM-dd") Since we are going to convert the format "yyyy-MM-dd hh:mm:ss" to "yyyy-MM-dd", the LocalDatetime is the right class. You can choose the correct class depending on your pattern. The DateTimeFormatter class is used to format and parse the date in Java 8 and LocalDateTime represents a date with time in the local timezone. The steps are exactly the same but instead of using SimpleDateFormat and Date class, we'll use the DateTimeFormatter and LocalDateTime class. You can use the DateTimeFormatter class in JDK 8 to change the date format of String in Java 8.
JAVA SETDATE HOW TO
How to change the format of Date in Java String using JDK 8 If you are interested to learn more about this API and other interesting Java 8 features I suggest you pick an up-to-date course like The Complete Java MasterClass, which is recently updated to cover the latest Java version. This means, unlike SimpleDateFormat class, DateTimeFormatter is both thread-safe and immutable, as well easier to use which so many predefined formats.

The old API was non-intuitive, not thread-safe, and mutable but the new API has corrected all that mistake. The new Date and Time API has built upon lessons learned from the previous failed attempt at creating a good date, time, and calendar API. In this article, I'll give you an example of both before and after JDK 8 so that you can change the date format of String in Java 8 or before, but before that let's see what's the difference between SimpleDateFormat and DateTimeFormatter class.

If you already know how to convert a date to String then it's pretty easy for you but if you don't know when you need to learn about DateFormat classes like SimpleDateFormat in JDK 6 or 7 and the from the new Date and Time API in JDK 8. The same process is repeated in both Java 8 and before, only corresponding API and class changes. In the first step, you need to parse String to create an equivalent date using the current format, and then once you got the date, you need to again convert it back to String using the new format. How will you do that? Well, it's not that difficult. For example, you have something like " 20:10:00" and you want to convert it that date into "", or you want to convert from dd-MM-YY to MM-dd-YY or to any other format of your choice and need, but a valid date format as per Java specification. One of the common programming tasks in Java is to change the date format of a given Date or String.
