How do I convert between old Date and Calendar object with the new Java 8 Date Time?

In this example we will learn how to convert the old java.util.Date and java.util.Calendar objects to the new Date Time introduced in Java 8. The first method in the code snippet below dateToNewDate() show conversion of java.util.Date while the calendarToNewDate() show the conversion of java.util.Calendar.

The java.util.Date and java.util.Calendar provide a toInstant() method to convert the objects to the new Date Time API class of the java.time.Instant. To convert the old date into the Java 8 LocalDate, LocalTime and LocalDateTime we first can create an instance of ZonedDateTime using the atZone() method of the Instant class.

ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());

From an instance of ZonedDateTime class we can call the toLocalDate(), toLocalTime() and toLocalDateTime() to get instance of LocalDate, LocalTime and LocalDateTime.

To convert back from the new Java 8 date to the old java.util.Date we can use the Date.from() static factory method and passing and instance of java.time.Instant that we can obtain by calling the following code.

Instant instant1 = dateTime.atZone(ZoneId.systemDefault()).toInstant();
Date now1 = Date.from(instant1);

Here are the complete code snippet to convert java.util.Date to the new Java 8 Date Time.

private static void dateToNewDate() {
    Date now = new Date();
    Instant instant = now.toInstant();

    ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());

    LocalDate date = zonedDateTime.toLocalDate();
    LocalTime time = zonedDateTime.toLocalTime();
    LocalDateTime dateTime = zonedDateTime.toLocalDateTime();

    Instant instant1 = dateTime.atZone(ZoneId.systemDefault()).toInstant();
    Date now1 = Date.from(instant1);

    System.out.println("java.util.Date          = " + now);
    System.out.println("java.time.LocalDate     = " + date);
    System.out.println("java.time.LocalTime     = " + time);
    System.out.println("java.time.LocalDateTime = " + dateTime);
    System.out.println("java.util.Date          = " + now1);
    System.out.println();
}

The steps for converting from the java.util.Calendar to the new Java 8 date can be seen in the code snippet below. As with java.util.Date the Calendar class provide toInstant() method to convert the calendar to java.time.Instant object.

Using the LocalDateTime.ofInstant() method we can create a LocalDateTime object from the instant object. By having the LocalDateTime object we can then get an instance of LocalDate and LocalTime by calling the toLocalDate() and toLocalTime() method.

Finally, to convert back to java.util.Calendar we can use the GregorianCalendar.from() static factory method which require an instance of ZonedDateTime to be passed as a parameter. To get an instance of ZonedDateTime we can call LocalDateTime.atZone() method. You can see the complete code in the code snippet below.

private static void calendarToNewDate() {
    Calendar now = Calendar.getInstance();

    LocalDateTime dateTime = LocalDateTime.ofInstant(now.toInstant(),
            ZoneId.systemDefault());

    LocalDate date = dateTime.toLocalDate();
    LocalTime time = dateTime.toLocalTime();

    ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.systemDefault());
    Calendar now1 = GregorianCalendar.from(zonedDateTime);

    System.out.println("java.util.Calendar      = " + now);
    System.out.println("java.time.LocalDateTime = " + dateTime);
    System.out.println("java.time.LocalDate     = " + date);
    System.out.println("java.time.LocalTime     = " + time);
    System.out.println("java.util.Calendar      = " + now1);
}

Below is the main Java class to run the code snippet. You must place the above methods inside this class to run the code snippet.

package org.kodejava.datetime;

import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class LegacyDateCalendarToNewDateExample {
    public static void main(String[] args) {
        dateToNewDate();
        calendarToNewDate();
    }
}

Here are the result of the code snippet above. The first group is conversion the java.util.Date to the new Date Time API. The second group is conversion from the java.util.Calendar to the new Date Time API.

java.util.Date          = Tue Nov 16 08:44:51 CST 2021
java.time.LocalDate     = 2021-11-16
java.time.LocalTime     = 08:44:51.031
java.time.LocalDateTime = 2021-11-16T08:44:51.031
java.util.Date          = Tue Nov 16 08:44:51 CST 2021

java.util.Calendar      = java.util.GregorianCalendar[time=1637023491089,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2021,MONTH=10,WEEK_OF_YEAR=47,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=320,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=44,SECOND=51,MILLISECOND=89,ZONE_OFFSET=28800000,DST_OFFSET=0]
java.time.LocalDateTime = 2021-11-16T08:44:51.089
java.time.LocalDate     = 2021-11-16
java.time.LocalTime     = 08:44:51.089
java.util.Calendar      = java.util.GregorianCalendar[time=1637023491089,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2021,MONTH=10,WEEK_OF_YEAR=46,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=320,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=44,SECOND=51,MILLISECOND=89,ZONE_OFFSET=28800000,DST_OFFSET=0]

How do I convert double value into int value?

To convert double value into an int value we can use type casting or using the Double.intValue() method call. The code snippet below show you how to do it.

package org.kodejava.basic;

public class DoubleToInt {
    public static void main(String[] args) {
        Double numberA = 49.99;
        System.out.println("numberA = " + numberA);

        // Converting Double value to int value by calling
        // the Double.intValue() method.
        int numberB = numberA.intValue();
        System.out.println("numberB = " + numberB);

        // Converting Double value to int value by casting
        // the primitive double value of the Double instance
        int numberC = (int) numberA.doubleValue();
        System.out.println("numberC = " + numberC);

        double numberD = 99.99;
        System.out.println("numberD = " + numberD);

        // Converting double value into int value using
        // type casting
        int numberE = (int) numberD;
        System.out.println("numberE = " + numberE);
    }
}

How do I convert angle from radians to degrees?

The example below show you how to convert an angle measured in radians into degrees and vice versa. We can use the Math.toDegrees() and Math.toRadians() method call to do the conversion.

package org.kodejava.math;

public class RadiansDegreeConversionExample {
    public static void main(String[] args) {
        double radians = 1.0d;
        double degrees = 45d;

        // Converts an angle measured in radians to an
        // approximately equivalent angle measured in
        // degrees.
        double toDegree = Math.toDegrees(radians);

        // Converts an angle measured in degrees to an
        // approximately equivalent angle measured in
        // radians.
        double toRadians = Math.toRadians(degrees);

        System.out.println("Radians " + radians + " in degrees  = " + toDegree);
        System.out.println("Degrees " + degrees + " in radians = " + toRadians);
    }
}

The result of the snippet above are:

Radians 1.0 in degrees  = 57.29577951308232
Degrees 45.0 in radians = 0.7853981633974483

How do I convert BigInteger into another radix number?

In this example you’ll see how we can convert a java.math.BigInteger number into another radix such as binary, octal and hexadecimal.

package org.kodejava.math;

import java.math.BigInteger;

public class BigIntegerConversion {
    public static void main(String[] args) {
        BigInteger number = new BigInteger("2021");
        System.out.println("Number      = " + number);
        System.out.println("Binary      = " + number.toString(2));
        System.out.println("Octal       = " + number.toString(8));
        System.out.println("Hexadecimal = " + number.toString(16));

        number = new BigInteger("FF", 16);
        System.out.println("Number      = " + number);
        System.out.println("Number      = " + number.toString(16));
    }
}

The result of our examples:

Number      = 2021
Binary      = 11111100101
Octal       = 3745
Hexadecimal = 7e5
Number      = 255
Number      = ff

How do I convert InputStream to String?

This example will show you how to convert an InputStream into String. In the code snippet below we read a data.txt file, could be from common directory or from inside a jar file.

package org.kodejava.io;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class StreamToString {

    public static void main(String[] args) throws Exception {
        StreamToString demo = new StreamToString();

        // Get input stream of our data file. This file can be in
        // the root of your application folder or inside a jar file
        // if the program is packed as a jar.
        InputStream is = demo.getClass().getResourceAsStream("/student.csv");

        // Call the method to convert the stream to string
        System.out.println(demo.convertStreamToString(is));
    }

    private String convertStreamToString(InputStream stream) throws IOException {
        // To convert the InputStream to String we use the
        // Reader.read(char[] buffer) method. We iterate until the
        // Reader return -1 which means there's no more data to
        // read. We use the StringWriter class to produce the string.
        if (stream != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try (stream) {
                Reader reader = new BufferedReader(new InputStreamReader(stream,
                        StandardCharsets.UTF_8));
                int length;
                while ((length = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, length);
                }
            }
            return writer.toString();
        }
        return "";
    }
}

How do I convert decimal to octal?

From the code snippet below you will learn how to convert decimal to an octal string and converting back from a string of octal number to decimal. For the first conversion we can utilize the Integer.toOctalString() method. This method takes an integer number and will return the string that represent the corresponding octal number.

To convert back from octal string to decimal number we can use the Integer.parseInt() method. Which require two parameter, a string that represent an octal number, and the radix which is 8 from octal number.

package org.kodejava.lang;

public class IntegerToOctalExample {
    public static void main(String[] args) {
        int integer = 1024;
        // Converting integer value to octal string representation.
        String octal = Integer.toOctalString(integer);
        System.out.printf("Octal value of %d is '%s'.\n", integer, octal);

        // Now we converting back from octal string to integer
        // by calling Integer.parseInt and passing 8 as the radix.
        int original = Integer.parseInt(octal, 8);
        System.out.printf("Integer value of octal '%s' is %d.%n", octal, original);

        // When for formatting purposes we can actually use printf
        // or String.format to display an integer value in other
        // format (o = octal, h = hexadecimal).
        System.out.printf("Octal value of %1$d is '%1$o'.\n", integer);
    }
}

Here is the result of our program.

Octal value of 1024 is '2000'.
Integer value of octal '2000' is 1024.
Octal value of 1024 is '2000'.

How do I convert decimal to binary?

In this example you will learn how to convert decimal number to binary number. To convert decimal number to binary we can use Integer.toBinaryString() method. This method takes a single parameter of integer and return a string that represent the equal binary number.

If you want to convert the other way around, from binary string to decimal, you can use the Integer.parseInt() method. This method takes two parameters. First, the string that represents a binary number to be parsed. The second parameter is the radix to be used while parsing, in case for binary number the radix is 2.

package org.kodejava.lang;

public class IntegerToBinaryExample {
    public static void main(String[] args) {
        int integer = 127;
        String binary = Integer.toBinaryString(integer);
        System.out.println("Binary value of " + integer + " is "
                + binary + ".");

        int original = Integer.parseInt(binary, 2);
        System.out.println("Integer value of binary '" + binary
                + "' is " + original + ".");
    }

}

Here is the result of our program.

Binary value of 127 is 1111111.
Integer value of binary '1111111' is 127.

How do I convert decimal to hexadecimal?

To convert decimal number (base 10) to hexadecimal number (base 16) we can use the Integer.toHexString() method. This method takes an integer as parameter and return a string that represent the number in hexadecimal.

To convert back the number from hexadecimal to decimal number we can use the Integer.parseInt() method. This method takes two argument, the number to be converted, which is the string that represent a hexadecimal number. The second argument is the radix, we pass 16 which tell the method if the string is a hexadecimal number.

package org.kodejava.lang;

public class ToHexadecimalExample {
    public static void main(String[] args) {
        // Converting a decimal value to its hexadecimal representation 
        // can be done using Integer.toHexString() method.
        System.out.println(Integer.toHexString(1976));

        // On the other hand to convert hexadecimal string to decimal
        // we can use Integer.parseInt(string, radix) method, 
        // where radix for hexadecimal is 16.
        System.out.println(Integer.parseInt("7b8", 16));
    }
}

How do I convert primitive boolean type into Boolean object?

The following code snippet demonstrate how to use the Boolean.valueOf() method to convert primitive boolean value or a string into Boolean object. This method will return the corresponding Boolean object of the given primitive boolean value.

When a string value is passed to this method it will return Boolean.TRUE when the string is not null, and the value is equal, ignoring case, to the string "true". Otherwise, it will return Boolean.FALSE object.

package org.kodejava.lang;

public class BooleanValueOfExample {
    public static void main(String[] args) {
        boolean b = true;
        Boolean bool = Boolean.valueOf(b);
        System.out.println("bool = " + bool);

        // Here we test the conversion, which is likely unnecessary. But
        // here is shown the boolean true is equals to Boolean.TRUE static
        // variable and of course you can guest the boolean false value is
        // equals to Boolean.FALSE
        if (bool.equals(Boolean.TRUE)) {
            System.out.println("bool = " + bool);
        }

        // On the line below we convert a string to Boolean, it returns
        // true if and only if the string is equals to "true" otherwise it
        // returns false
        String s = "false";
        Boolean bools = Boolean.valueOf(s);
        System.out.println("bools = " + bools);

        String f = "abc";
        Boolean abc = Boolean.valueOf(f);
        System.out.println("abc = " + abc);
    }
}

The code snippet will print the following output:

bool = true
bool = true
boolS = false
abc = false

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