SoFunction
Updated on 2025-05-15

Detailed explanation of how to convert strings into dates in Java date processing

Problem description

Enter "2015-10-20", output: "2015-October-20 is Tuesday, the 293rd day of 2015"

Solution

Here is the complete Java code implementation:

import ;
import ;
import ;
import ;
import ;
import ;

public class EnhancedDateConverter {
    
    private static final String[] WEEK_NAMES = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    private static final DateTimeFormatter INPUT_FORMATTER = ("yyyy-MM-dd");
    private static final DateTimeFormatter OUTPUT_FORMATTER = ("yyyyy year-MM month-dd day");
    
    public static void main(String[] args) {
        Scanner sc = new Scanner();
        
        while (true) {
            ("Please enter a date(Format: yyyy-MM-dd),enterexitquit:");
            String input = ().trim();
            
            if ("exit".equalsIgnoreCase(input)) {
                break;
            }
            
            try {
                LocalDate date = parseDate(input);
                String formattedDate = formatDate(date);
                String weekDay = getChineseWeekDay(date);
                int dayOfYear = getDayOfYear(date);
                
                ("%s is %s, which is the %d day %n in the year %d",
                        formattedDate, weekDay, (), dayOfYear);
                
            } catch (DateTimeParseException e) {
                ("The date format is incorrect, please use the yyyy-MM-dd format");
            }
        }
        
        ();
    }
    
    private static LocalDate parseDate(String dateStr) throws DateTimeParseException {
        return (dateStr, INPUT_FORMATTER);
    }
    
    private static String formatDate(LocalDate date) {
        return (OUTPUT_FORMATTER);
    }
    
    private static String getChineseWeekDay(LocalDate date) {
        DayOfWeek dayOfWeek = ();
        return WEEK_NAMES[() % 7];
    }
    
    private static int getDayOfYear(LocalDate date) {
        return ();
    }
}

Example of usage

Please enter the date (format: yyyy-MM-dd), enter exit to exit:
2023-05-15
2023-May-15 is Monday, the 135th day of 2023

Please enter the date (format: yyyy-MM-dd), enter exit to exit:
2020-02-29
2020-February-29 is Saturday, the 60th day of 2020

Please enter the date (format: yyyy-MM-dd), enter exit to exit:
2023-13-01
The date format is incorrect, please use the yyyy-MM-dd format

Please enter the date (format: yyyy-MM-dd), enter exit to exit:
exit

Method supplement

Here are several ways to convert a String object to a Date object. We will open the DateTime from Java 8 and then view the data type that is also used to represent the date.

Finally, we will take a look at the external libraries for converting the DateUtils class in Joda-Time and Apache Commons Lang.

1. Convert string to LocalDate or LocalDateTime

LocalDate and LocalDateTime are immutable date-time objects, representing date, date and time respectively. By default, Java dates are in ISO-8601 format, so how about we have any string representing dates and times in this format, we can use the parse() API of these classes directly.

Using the Parse API

The Date-Time API provides the parse() method to parse a String containing date and time information. To convert a String object to LocalDate and LocalDateTime objects, the String must represent a valid date or time, according to ISO_LOCAL_DATE or ISO_LOCAL_DATE_TIME. Otherwise, a DateTimeParseException will be thrown at runtime.

In the following example, we convert String to LocalDate:

LocalDate date = ("2018-05-05");

You can convert String to LocalDateTime using a similar method above:

LocalDateTime dateTime = ("2018-05-05T11:50:55");

One thing to note is that LocalDate and LocalDateTime objects are time zone agnostic. However, when we need to deal with dates and times in a specific time zone, we can directly use the parse method of ZonedDateTime to get the date and time of a specific time zone:

DateTimeFormatter formatter = ("yyyy-MM-dd HH:mm:ss z");
ZonedDateTime zonedDateTime = ("2015-05-05 10:15:30 Europe/Paris", formatter);

Now let's see how to convert strings to custom formats.

Use the Parse API and customize the format

Converting a custom-formatted String to a Date object is a common operation in Java.

For this we will use the DateTimeFormatter class, which provides many predefined formatters and allows us to customize the formatting.

Let's start with the predefined format of getDateTimeFormatter:

String dateInString = "19590709";
LocalDate date = (dateInString, DateTimeFormatter.BASIC_ISO_DATE);

In the next example, let's create a date format with the format "EEE, d MMM yyyy". This format specifies three characters as the entire journey of the week, one number represents the date in the month, three characters represent the month, and four digits represent the year.

This format recognizes strings such as: "Fri, 3 Jan 2003" or "Wed, 23, Mar 1994".

String dateInString = "Mon, 05 May 1980";
DateTimeFormatter formatter = ("EEE, d MMM yyyy", );
LocalDate dateTime = (dateInString, formatter);

Common date and time formats

Let's take a look at several commonly used date and time formats:

  • y – Year (1996; 96)
  • M – Month in year (July; Jul; 07)
  • d – Day in month (1-31)
  • E – Day name in week (Friday, Sunday)
  • a AM/PM marker (AM, PM)
  • H – Hour in day (0-23)
  • h – Hour in AM/PM (1-12)
  • m – Minute in hour (0-60)
  • s – Second in minute (0-60)

2. Convert string to

Prior to Java 8, the Java date and time mechanism was provided by the old API of the ,and classes, and we still need to use it sometimes.

Let's see how to convert a String to an object.

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", );

String dateInString = "7-Jun-2013";
Date date = (dateInString);

In the above example, we first need to construct a SimpleDateFormat object by passing a pattern describing the date and time format.

Next we need to call the parse() method that passes the date String. If the passed String parameter is different from the format of the pattern, a ParseException is thrown.

Set time zone information *

It should be noted that there is no time zone concept, and it only represents the number of seconds elapsed since 1970-01-01T00:00:00Z.

However, when we print the Date object directly, it always prints the Java default system time zone.

In the following example, we will learn how to format the date while adding time zone information:

SimpleDateFormat formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a", );
(("America/New_York"));

String dateInString = "22-01-2015 10:15:55 AM"; 
Date date = (dateInString);
String formattedDateString = (date);

We can also programmatically change the time zone information of the JVM, but it is not recommended to do this:

(("GMT"));

3. Use third-party libraries

Now that we have a good understanding of how to convert String objects into Date objects using the old and new APIs provided by core Java, let's look at some external libraries below.

Joda-Time Library

Joda-Time is an alternative to the core Java Date and Time libraries. Although the author now recommends that users move to JSR-310, if they can't do it in the short term, the Joda-TIme library provides an excellent alternative to handling dates and times. This library provides almost all the features supported by the Java8 Date Time project.

First, you need to add dependencies to the project:

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10</version>
</dependency>

Here is a simple example using standard DateTime:

DateTimeFormatter formatter = ("dd/MM/yyyy HH:mm:ss");

String dateInString = "07/06/2013 10:11:59";
DateTime dateTime = (dateInString, formatter);

Let's take a look at an example of explicitly setting the time zone:

DateTimeFormatter formatter = ("dd/MM/yyyy HH:mm:ss");

String dateInString = "07/06/2013 10:11:59";
DateTime dateTime = (dateInString, formatter);
DateTime dateTimeWithZone = (("Asia/Kolkata"));

Apache Commons Lang – DateUtils

The DateUtils class provides many useful and practical methods to make it easier when using older versions of Calendar and Date objects.

Add dependencies before use:

<dependency>
    <groupId></groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Let's convert String to Date using the date pattern defined in the array:

String dateInString = "07/06-2013";
Date date = (dateInString, new String[] { "yyyy-MM-dd HH:mm:ss", "dd/MM-yyyy" });

This is the end of this article about the detailed explanation of the method of converting strings into dates in Java date processing. For more related content on Java string conversion, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!