How do I convert date string from one format to another format?

In the following code snippet we will see hot to change a date from one format to another format. For example from 2024-11-04 to 04-Nov-24 format in Java. We can use the DateTimeFormatter class from the java.time.format package to do the conversion.

The steps are:

  • Parse the original date string.
  • Format it to the desired pattern.

Here’s the complete code to do this:

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateFormatConversion {
    public static void main(String[] args) {
        // The original date string
        String originalDate = "2024-11-04";

        // Define the input and output date formats
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MMM-yy");

        // Parse the original date
        LocalDate date = LocalDate.parse(originalDate, inputFormatter);

        // Format the date to the desired pattern
        String formattedDate = date.format(outputFormatter);

        // Print the formatted date
        System.out.println(formattedDate);
    }
}

Output:

04-Nov-24

In the code above we define two formatters, one for the original date format, and the second one is for the new date format. The input formatter matches the original date format (yyyy-MM-dd). The output formatter specifies the desired format (dd-MMM-yy).

We use the LocalDate.parse() method to parse the string of original date into a LocalDate object. Next, we use the LocalDate.format() method to convert into a new date format using the defined formatter object.

This approach uses java.time API introduced in Java 8, which is the recommended way to handle date and time in Java due to its immutability and thread-safety features.

How do I convert datetime string with optional part to a date object?

Since JDK 8, we can create a datetime formatter / parser pattern that can have optional sections. When parsing a datetime string that contains optional values, for example, a date without time part or a datetime without second part, we can create a parsing pattern wrapped within the [] symbols. The [ character is the optional section start symbol, and the ] character is the optional section end symbol. The pattern inside this symbol will be considered as an optional value.

We can use the java.time.format.DateTimeFormatter class to parse the string of datetime or format the datetime object, and use it with the new Java time API classes such as java.time.LocalDate or java.time.LocalDateTime to convert the string into respective LocalDate or LocalDateTime object as show in the code snippet below.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeParseOptionalParts {
    public static final String OPT_TIME_PATTERN = "yyyy-MM-dd[ HH:mm[:ss]]";
    public static final String OPT_SECOND_PATTERN = "yyyy-MM-dd HH:mm[:ss]";

    public static void main(String[] args) {
        DateTimeFormatter optTimeFormatter = DateTimeFormatter.ofPattern(OPT_TIME_PATTERN);
        LocalDate date1 = LocalDate.parse("2023-08-28", optTimeFormatter);
        LocalDate date2 = LocalDate.parse("2023-08-28 17:15", optTimeFormatter);
        LocalDate date3 = LocalDate.parse("2023-08-28 17:15:30", optTimeFormatter);
        System.out.println("date1 = " + date1);
        System.out.println("date2 = " + date2);
        System.out.println("date3 = " + date3);

        DateTimeFormatter optSecondFormatter = DateTimeFormatter.ofPattern(OPT_SECOND_PATTERN);
        LocalDateTime datetime1 = LocalDateTime.parse("2023-08-28 17:15", optSecondFormatter);
        LocalDateTime datetime2 = LocalDateTime.parse("2023-08-28 17:15:30", optSecondFormatter);
        System.out.println("datetime1 = " + datetime1);
        System.out.println("datetime2 = " + datetime2);
    }
}

Here are the outputs of the code snippet above:

date1 = 2023-08-28
date2 = 2023-08-28
date3 = 2023-08-28
datetime1 = 2023-08-28T17:15
datetime2 = 2023-08-28T17:15:30

How do I parse negative number in parentheses?

In financial application negative numbers are often represented in parentheses. In this post we will learn how we can parse or convert the negative number in parentheses to produce the represented number value. To parse text / string to a number we can use the java.text.DecimalFormat class.

Beside number in parentheses, in this example we also parse negative number that use the minus sign with the currency symbol like $. Let’s jump to the code snippet below:

package org.kodejava.text;

import java.text.DecimalFormat;

public class NegativeNumberParse {
    // Pattern for parsing negative number.
    public static final String PATTERN1 = "#,##0.00;(#,##0.00)";
    public static final String PATTERN2 = "$#,##0.00;-$#,##0.00";

    public static void main(String[] args) throws Exception {
        DecimalFormat df = new DecimalFormat(PATTERN1);

        String number1 = "(1000)";
        String number2 = "(1,500.99)";

        System.out.println("number1 = " + df.parse(number1));
        System.out.println("number2 = " + df.parse(number2));

        df = (DecimalFormat) DecimalFormat.getInstance();
        df.applyPattern(PATTERN2);

        String number3 = "-$1000";
        String number4 = "-$1,500.99";

        System.out.println("number3 = " + df.parse(number3));
        System.out.println("number4 = " + df.parse(number4));
    }
}

And here are the results of our code snippet above:

number1 = -1000
number2 = -1500.99
number3 = -1000
number4 = -1500.99

If you need to display or format negative numbers in parentheses you can take a look at the following example How do I display negative number in parentheses?.

Can I create a boolean variable from string?

To convert a string into boolean we can use the Boolean.parseBoolean(String) method. If we pass a non null value that equals to true, ignoring case, this method will return true value. Given other values it will return a false boolean value.

package org.kodejava.lang;

public class BooleanParseExample {
    public static void main(String[] args) {
        // Parsing string "true" will result boolean true
        boolean boolA = Boolean.parseBoolean("true");
        System.out.println("boolA = " + boolA);

        // Parsing string "TRUE" also result boolean true, as the
        // parsing method is case insensitive
        boolean boolB = Boolean.parseBoolean("TRUE");
        System.out.println("boolB = " + boolB);

        // The operation below will return false, as Yes is not
        // a valid string value for boolean expression
        boolean boolC = Boolean.parseBoolean("Yes");
        System.out.println("boolC = " + boolC);

        // Parsing a number is also not a valid expression so the
        // parsing method return false
        boolean boolD = Boolean.parseBoolean("1");
        System.out.println("boolD = " + boolD);
    }
}

The code snippet above will print the following output:

boolA = true
boolB = true
boolC = false
boolD = false

How do I check if a string is a valid number?

When building a computer program we will use a lot of string to represent our data. The data might not just information about our customer name, email or address, but will also contain numeric data represented as string. So how do we know if this string contains a valid number?

Java provides some wrappers to the primitive data types that can be used to do the checking. These wrappers come with the parseXXX() method such as Integer.parseInt(), Float.parseFloat() and Double.parseDouble() methods.

package org.kodejava.lang;

public class NumericParsingExample {
    public static void main(String[] args) {
        String age = "15";
        String height = "160.5";
        String weight = "55.9";

        try {
            int theAge = Integer.parseInt(age);
            float theHeight = Float.parseFloat(height);
            double theWeight = Double.parseDouble(weight);

            System.out.println("Age    = " + theAge);
            System.out.println("Height = " + theHeight);
            System.out.println("Weight = " + theWeight);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}

In the example code we use Integer.parseInt(), Float.parseFloat(), Double.parseDouble() methods to check the validity of our numeric data. If the string is not a valid number java.lang.NumberFormatException will be thrown.

The result of our example:

Age    = 15
Height = 160.5
Weight = 55.9