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();

        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) {

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

How do I convert String to Date object in Java?

The following code shows how we can convert a string representation of date into java.util.Date object.

To convert a string of date we can use the help from java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.

package org.kodejava.text;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class ConvertStringToDateExample {
    public static void main(String[] args) {
        String pattern = "dd/MM/yyyy";
        String date = "15/09/2021";

        try {
            DateFormat df = new SimpleDateFormat(pattern);
            Date today = df.parse(date);
            System.out.println("Today = " + df.format(today));
        } catch (ParseException e) {

        // Using Java 8 Date and Time
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDate localDate = LocalDate.parse(date, formatter);
        System.out.println("Today = " + localDate.format(formatter));

And here is the result of our code:

Today = 15/09/2021
Today = 15/09/2021

The example starts by creating an instance of SimpleDateFormat with dd/MM/yyyy format which mean that the date string is formatted in day-month-year sequence.

Finally, using the parse(String source) method we can get the Date instance. Because parse method can throw java.text.ParseException exception if the supplied date is not in a valid format; we need to catch it.

Here are the list of defined patterns that can be used to format the date taken from the Java class documentation.

Letter Date / Time Component Examples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800