0 0
WP Ad Inserter plugin
Read Time:17 Minute, 28 Second

Table of Contents

Changing the date format of a given Date or String is a typical Java programming task. For example, suppose you have “2022-05-22 12:00:00” and want to convert it to “2022-05-22,” or convert from dd-MM-YY to MM-dd-YY, or any other format you like, as long as it is a valid date format as defined by Java. How will you accomplish this? It’s not that difficult, after all. It’s a simple two-step procedure.

It would help if you first parsed String to construct an equivalent date in the existing format and then converted the date back to String in the new format. The approach is similar to Java 8 and earlier, except for API and class changes.

The format() function of the java.text.DateFormat package is used to convert Date to String in Java.

The java.text.SimpleDateFormat class is used to parse, and format dates according to a custom formatting pattern. The Java SimpleDateFormat usually uses a Java String as a source when processing dates. When formatting dates, the SimpleDateFormat converts a Date object to a String, but it can also convert a Date object to a StringBuffer. The SimpleDateFormat class is responsible for formatting dates in this text.

SimpleDateFormat creation

Create a SimpleDateFormat object like follows:

SUGGESTED READ

String datePattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);

The date parsing and formatting pattern are specified by the pattern parameter supplied to the SimpleDateFormat constructor. A standard Java String is used as the pattern.

Date Formatting

Once you’ve generated a SimpleDateFormat instance, you can use its format() function to format dates. Consider the following scenario:

String datePattern = "yyyy-MM-dd";
SimpleDateFormat simpleFormat = new SimpleDateFormat(datePattern); String newDate = simpleFormat.format(new Date());
System.out.println(newDate);

The format() function takes a java.util.Date instance as an argument. The following is the output of the SimpleDateFormat example:

2022-05-22

Take note of how the formatted date string begins with the year, month, and day. The date pattern supplied to the SimpleDateFormat constructor determines the order of the date fields. As previously stated, this format is discussed further in this Java SimpleDateFormat lesson.

StringBuffer with Date Format

Instead of returning an individual String with the date prepared, the Java SimpleDateFormat class can format a Date object into a StringBuffer. It is accomplished through the SimpleDateFormat class’s format() method, which takes the Date, StringBuffer, and a FieldPosition instance as inputs. Here’s an example of using Java SimpleDateFormat to format a date into a StringBuffer:

SUGGESTED READ

StringBuffer strBuffer = new StringBuffer();
Date dateNow = new Date(); SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
simpleFormat.format(dateNow, strBuffer, new FieldPosition(0));

It’s unclear how the FieldPosition instance is employed. Whatever the int value supplied to the FieldPosition constructor is, the format() method appends the formatted String to the end of the StringBuffer.

Parsing Dates

The parse() method of the SimpleDateFormat class converts a String to a java.util.Date instance. Consider the following scenario:

String datePattern = "yyyy-MM-dd";
SimpleDateFormat simpleFormat = new SimpleDateFormat(datePattern); Date newDate = simpleFormat.parse("2022-05-22");

After this code is run, the date variable points to a Date instance reflecting May 22nd, 2022.

Creating a Locale-Specific SimpleDateFormat

A SimpleDateFormat instance is created for a specified Java Locale. The dates will be formatted according to the Locale when this is done. A formatting pattern that includes the name of the weekday, for example, will write the weekday in the chosen Locale’s language. Consider the following scenario:

String newPattern = "EEEEE dd MMMMM yyyy HH:mm:ss.SSSZ";
SimpleDateFormat sdFormat = new SimpleDateFormat(newPattern, new Locale("da", "DK")); String dateNow = sdFormat.format(new Date());
System.out.println(dateNow);

Characters other than these will be inserted into the pattern as normal text and hence into the formatted dates. Some characters are used in several combinations. For example, you can write yy for a two-character version of the year (e.g., 22) or yyyy for a four-character version of the year.(e.g. 2022). See the JavaDoc for the SimpleDateFormat class for further information on the acceptable patterns.

SUGGESTED READ

Examples of Patterns

Here are some instances of Java SimpleDateFormat date patterns:

dd-MM-yy 22-05-22
dd-MM-yyyy 22-05-2022
MM-dd-yyyy 05-22-2022
yyyy-MM-dd 2022-05-31
yyyy-MM-dd HH:mm:ss 2022-05-22 23:59:59
yyyy-MM-dd HH:mm:ss.SSS 2022-05-22 23:59:59.999
yyyy-MM-dd HH:mm:ss.SSSZ 2022-05-22 23:59:59.999+0100
EEEEE MMMMM yyyy HH:mm:ss.SSSZ Sunday May 2022 12:45:42.720+0100

DateFormatSymbols

You can change the date symbols used in the formatted output for a certain Locale. A java.text is used to accomplish this. Instance of DateFormatSymbols. Consider the following scenario:

Locale newLocale = new Locale("en", "UK");
DateFormatSymbols codeDateFormatSymbols = new DateFormatSymbols(newLocale);
codeDateFormatSymbols.setWeekdays(new String[]{ "null", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
}); String newPattern = "EEEEE MMMMM yyyy";
SimpleDateFormat simpleFormat = new SimpleDateFormat(newPattern, dateFormatSymbols); String newDate = simpleFormat.format(new Date());
System.out.println(newDate);

Second, a new set of weekday names has been established. You should note that the initial String, “unused,” is never used. To be indexable by the Calendar.SUNDAY, Calendar.MONDAY and other constants, the indices in this array must begin with one. Calendar.SUNDAY is 1, Calendar.MONDAY is 2, and so on. Third, using the DateFormatSymbols, a SimpleDateFormat is built, and the date is formatted. The following is an example of what the output could look like:

Sunday, May 2022

Take note of how the custom weekday name is employed. On the DateFormatSymbols instance, you can add extra date formatting symbols. The following are the procedures for adding extra symbols:

dateFormatSymbols.setWeekdays();
dateFormatSymbols.setAmPmStrings();
dateFormatSymbols.setEras();
dateFormatSymbols.setShortWeekdays();
dateFormatSymbols.setZoneStrings();
dateFormatSymbols.setLocalPatternChars();
dateFormatSymbols.setMonths();
dateFormatSymbols.setShortMonths();

SimpleDateFormat’s Time Zone setting

So far, all of the examples in this lesson have used the system default time zone. If you want to format a date, the SimpleDateFormat will presume you want to format it according to the system’s time zone. This, however, may not always be the case.

SUGGESTED READ

The setTimeZone() method of a SimpleDateFormat changes the time zone. The setTimeZone() function takes as an argument a Java TimeZone instance (java.util.TimeZone). Here’s an example of how to change a Java SimpleDateFormat instance’s time zone:

SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ"); simpleFormat.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));

The SimpleDateFormat will modify its formatting once the time zone is set. Here’s an example of changing the time zone to two distinct time zones while formatting the same date:

Date dateNow = new Date(); SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ"); sdFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println(sdFormat .format(dateNow)); sdFormat.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
System.out.println(sdFormat .format(dateNow));

DateFormat’s format() method

To convert a Date to a String, utilize the format() function of the DateFormat class. DateFormat is a generic type. SimpleDateFormat is a DateFormat child class. It’s how the DateFormat class is implemented. The format() method’s signature is as follows:

String format(Date d) 

Example of Java Date to String

Let’s look at a simple Java code to convert Date to String.

Date newDate = Calendar.getInstance().getTime(); DateFormat codeDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss"); String stringDate = codeDateFormat.format(newDate); import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Calendar; public class DateToStringExample1 { public static void main(String args[]){ Date date = Calendar.getInstance().getTime(); DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss"); String strDate = dateFormat.format(date); System.out.println("Converted String: " + strDate); } } 

Let’s take a look at the whole example of converting date and time to String in Java using the format() function of the java.text.SimpleDateFormat class.

SUGGESTED READ

 import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class CodeDateToString { public static void main(String[] args) { Date newDate = new Date(); SimpleDateFormat simpleFormatter = new SimpleDateFormat("MM/dd/yyyy"); String stringDate = simpleFormatter.format(newDate); System.out.println("The Date Format with is: MM/dd/yyyy : "+stringDate); simpleFormatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); stringDate = simpleFormatter.format(newDate); System.out.println("The Date Format with dd-M-yyyy hh:mm:ss is: "+stringDate); simpleFormatter = new SimpleDateFormat("dd MMMM yyyy"); stringDate = simpleFormatter.format(newDate); System.out.println("The Date Format with dd MMMM yyyy is: "+stringDate); simpleFormatter = new SimpleDateFormat("dd MMMM yyyy zzzz"); stringDate = simpleFormatter.format(newDate); System.out.println("The Date Format with dd MMMM yyyy zzzz is: "+stringDate); simpleFormatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z"); stringDate = simpleFormatter.format(newDate); System.out.println("The Date Format with E, dd MMM yyyy HH:mm:ss z is: "+stringDate); } } 

java.util.Date conversion to String

Although we shouldn’t utilize java.util.Date when dealing with Java 8, there are situations when we don’t have a choice (for example, when the Date object comes from a library we don’t control). In such circumstances, we have numerous options for converting java.util.Date to String.

Getting the Date Object Ready : Let’s start by declaring an anticipated String representation of our date and a date format pattern:

private static final String EXPECTED_STRING_DATE = "May 22, 2022 12:00 PM";
private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a";

Now we need an actual Date object to convert. To make it, we’ll utilize a Calendar instance:

TimeZone.setDefault(TimeZone.getTimeZone("CET"));
Calendar calendar = Calendar.getInstance();
calendar.set(2022, Calendar.MAY, 22, 12, 0);
Date date = calendar.getTime();

To avoid complications when working with the new API later, we’ve set the default TimeZone to CET. The Date object does not have a time zone, but its toString() method uses the current default time zone. This Date instance is used in all of the examples that follow.

Using the DateFormat Abstract Class

SimpleDateFormat is a subclass of the abstract DateFormat class, as we can see. This class contains methods for formatting dates and times. We’ll utilize it to get the same result as before:

SUGGESTED READ

String formattedDate = DateFormat .getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT) .format(date);

With this method, we’re passing style patterns — in our case, MEDIUM for the date and SHORT for the time.

The Formatter Class in Action

The Formatter class is another simple way to acquire the same String as previous instances. While it isn’t the most readable approach, it is a thread-safe one-liner that could be beneficial, especially in a multi-threaded environment (we should note that SimpleDateFormat isn’t thread-safe):

String strFormattedDate = String.format("%1$tb %1$te, %1$tY %1$tI:%1$tM %1$Tp", date);

We used 1$ to indicate that just one argument would be passed with each flag.

Using the Java 8 Date/Time API for conversion

We should use the Date/Time API from Java 8 instead of the java.util.Date and java.util.Calendar classes whenever possible. Let’s look at how we can use it to convert a Date object to a String. We’ll utilize the DateTimeFormatter class and its format() function this time, along with the same date pattern as above:

DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(DATE_FORMAT);

We must transform our Date object to an Instant object to use the new API:

SUGGESTED READ

Instant codeInstant = date.toInstant();

We must also convert the Instant object to LocalDateTime because our expected String has both date and time components:

LocalDateTime ldt = codeInstant .atZone(ZoneId.of("CET")) .toLocalDateTime();

Finally, we can get our formatted String with ease:

String formattedDate = ldt.format(formatter);

How to use JDK 8 to modify the date format in a Java string

To modify the date format of String in Java 8, use the DateTimeFormatter class in JDK 8. The procedures are the same, except we’ll use the DateTimeFormatter and LocalDateTime class instead of SimpleDateFormat and Date.

In Java 8, the DateTimeFormatter class format and parse dates, while LocalDateTime represents a date with local time. Depending on your pattern, you can select the appropriate class. The LocalDatetime class is appropriate for converting the format “yyyy-MM-dd hh:mm:ss” to “yyyy-MM-dd.” If your pattern only contains a date, a LocalDate class is used instead.

Anyway, here’s a code example from JDK 8 for changing the date format in a Java String:

SUGGESTED READ

DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter dtNewPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDateTime localDateTime = LocalDateTime.parse(input, dtFormatter);
String dateOutput = localDateTime.format(dtNewPattern);

The processes are the same, but the code is robust because of DateTimeFormatter’s expressiveness, thread safety, and immutability. In general, if you use JDK 8, use the new Date and Time API for any new code you develop that has anything to do with dates. Spend some time learning the fundamental classes, such as LocalDate, LocalTime, LocalDateTime, ZonedDateTime, DateTimeFormatter, etc. Most typical tasks have been simplified, such as converting a string to a date and vice versa, formatting and parsing dates, and extracting day, month, and year.

Modifying the date format in a Java String Before JDK 8

If you’re not using JDK 8, you’ll have to rely on the outdated date and calendar API. To alter the date format, use the SimpleDateFormat class. Here are the steps you must take:

1) Use the old approach to create a Date format.

SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

2) Convert String to Date using the following format:

Date newDate = simpleFormat.parse(input);

3) Add the new pattern to a DateFormat.

SUGGESTED READ

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

4) Using the new pattern’s Dateformatter, convert the date to a string.

String output = simpleDateFormat.format(date);

That’s all there is; you now have a String in the desired format. Though you should use the SimpleDateFormat class cautiously, it is not thread-safe and should not be shared in a multi-threading context. Because letters are case-sensitive, “yyyy-mm-dd” and “yyyy-MM-dd” are not interchangeable. The minuscule m stands for a minute, while the large M stands for a month.

Example: Program for formatting the current date to a String and prints it

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date; public class CodeDateToString {
// this is the main execution point of the program public static void main(String args[]) throws Exception,ParseException { // current date retrieval LocalDate localDate = LocalDate.now(); //Conversion of a LocalDate object to Date Date dateNow = java.sql.Date.valueOf(localDate); //SimpleDateFormat class instantiation SimpleDateFormat simpleFormatter = new SimpleDateFormat("dd-MM-yyyy"); //Formatting the date value obtained String dateFormatted = simpleFormatter.format(dateNow); System.out.println("Formatted date: "+dateFormatted); }
}

Example: Using LocalDate.toString() method

  • Get a LocalDate instance from date.
  • Use the toString() function of the LocalDate class to convert the given date to a string.
  • Print the outcome.
// program for converting Date to String in Java import java.time.LocalDate; class Codeunderscored { // Function for date to string conversion public static String convertDateToString(String newDate) { // Getting LocalTime instance from date LocalDate codeDate = LocalDate.parse(newDate); // Converting the date provided into a string through the toString()method String dateToString= codeDate.toString(); // returning the resultant outcome return (dateToString); } // This is the main methods' driver Code public static void main(String args[]) { // Date provided String newDate = "2022-05-22"; // Converting and printing the result System.out.print(convertDateToString(newDate)); }
}

Example: Using DateFormat.format() method

  • Get the date you want to convert.
  • When formatting the string representation of the date object, create an instance of the SimpleDateFormat class.
  • Using the Calendar object, get the current date.
  • The format() method converts a date into a string.
  • Print the outcome.
// program for converting the Date to String in Java import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat; class Codeunderscored { // Date to string conversion function public static String convertDateToString(String date) { //Converts a string into a date object. DateFormat dateFormat = new SimpleDateFormat(date); // Using the calendar object, get the date. Date codeToday = Calendar.getInstance().getTime(); // Using the format() method, convert the date to a string. String codeDateToString = dateFormat.format(codeToday); // Return the outcome return (codeDateToString); } // This is the main method public static void main(String args[]) { // Given Date String newDate = "07-27-2020"; // Conversion and result and printing System.out.print(convertDateToString(newDate)); }
}

Example: Program for converting Date from one format to another in Java

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date; public class CodeDateConversion { public static void main(String[] args) throws ParseException { String dateSample = "2022-05-22 20:10:00"; // prior to Java 8 SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = simpleFormat.parse(dateSample); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String dateOutput = dateFormat.format(date); System.out.println("Date in the old format is: " + dateSample); System.out.println("Updated Date in the new format: " + dateOutput); //Using the new Date alongside the Time API in Java 8 DateTimeFormatter dtPattern = DateTimeFormatter .ofPattern("yyyy-MM-dd HH:mm:ss"); DateTimeFormatter resultantPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDateTime localDateTime = LocalDateTime.parse(input, dtPattern); dateOutput = localDateTime.format(resultantPattern); System.out.println("Date in the old format (java 8) format : " + dateSample); System.out.println("The resultant Date in the new format (java 8) : " + dateOutput); } }

As we already stated, the stages are the same; just the classes alter. SimpleDateFormat and Date classes are used in Java 7 and earlier, while DateTimeFormatter and LocalDateTime classes are used in Java 8.

Important things to keep in mind

Converting a string to date may appear simple, but it is not. Due to the difficult syntax of a certain pattern for date format, many Java developers commit minor errors.

There are also some minor differences between JDK 8 and previous versions, which implies that a pattern that worked with SimpleDateFormat in JDK 8 may not work with DateTimeFormatter, an equivalent class from Java 8’s new Date and Time API. As a result, while providing a pattern, you must use caution.

SUGGESTED READ

When we first ran the application, we got the following error after copying the format from SimpleDateFormat to DateTimeFormatter in the previous code:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2022-05-22 20:10:00' could not be parsed: Invalid value
for ClockHourOfAmPm (valid values 1 - 12): 20
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at codeDateConversion.main(codeDateConversion.java:28)

The error message is clear: it expects 1 to 12 in the hour column, implying that it expects an AM/PM date rather than a 24-hour format. This was our pattern, “yyyy-MM-dd hh:mm:ss,” which used a little h, i.e. “hh,” to denote the hour of the day.

The mistake disappeared when we changed it to a capital H, i.e. “HH.” You may not have noticed a minor distinction while reading the code.

Another thing to remember is that the capital M, “MM,” is used for months while the little M, “mm,” is used for minutes. Many programmers commit this error while writing a date format pattern.

For example, to produce a date like 2022-05-22, you must use the pattern “dd-MM-yyyy,” not “dd-mm-yyyy,” which will not work but is easier to enter because both dd and yyyy are in a small case. We recommend taking thorough Java classes if you want to understand more about date formatting in Java.

SUGGESTED READ

Conclusion

In this tutorial, we’ve explored how to convert Date objects to String objects in Java. Note how we’ve used both the older java.util.Date type, java.util.Calendar classes and the new Date/Time API are introduced in Java 8. The Formatter class was then used, followed by the Java 8 Date/Time API.

For obvious reasons, we recommend using DateTimeFormatter instead of SimpleDateFormat if you’re using Java 8. Some of the outstanding reasons include immutability and thread safety.

That’s everything there is to know about changing the date format of a String in Java. We’ve seen how to accomplish it before and after JDK 8. As we previously stated, it’s a two-step process in which you convert String to date using the old date type and then back to String using the new date format.

Source: https://www.codeunderscored.com/how-to-format-a-date-to-string-in-java/

8 things about Records in C# you probably didn’t know Previous post 8 things about Records in C# you probably didn’t know
How to calculate the Absolute Value in Python Next post How to calculate the Absolute Value in Python

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.