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 obtains 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.example.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          = Mon Feb 01 11:09:55 WITA 2016
java.time.LocalDate     = 2016-02-01
java.time.LocalTime     = 11:09:55.746
java.time.LocalDateTime = 2016-02-01T11:09:55.746
java.util.Date          = Mon Feb 01 11:09:55 WITA 2016

java.util.Calendar      = java.util.GregorianCalendar[time=1454296195871,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Makassar",offset=28800000,dstSavings=0,useDaylight=false,transitions=5,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2016,MONTH=1,WEEK_OF_YEAR=6,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=32,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=9,SECOND=55,MILLISECOND=871,ZONE_OFFSET=28800000,DST_OFFSET=0]
java.time.LocalDateTime = 2016-02-01T11:09:55.871
java.time.LocalDate     = 2016-02-01
java.time.LocalTime     = 11:09:55.871
java.util.Calendar      = java.util.GregorianCalendar[time=1454296195871,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Makassar",offset=28800000,dstSavings=0,useDaylight=false,transitions=5,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2016,MONTH=1,WEEK_OF_YEAR=5,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=32,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=9,SECOND=55,MILLISECOND=871,ZONE_OFFSET=28800000,DST_OFFSET=0]

How do I convert JSON into object?

On the previous example, How do I convert object into JSON? we convert object into JSON string. In this example you will see how to do the opposite, converting JSON string back into object.

To convert JSON string to object use Gson.fromJson() method. This method takes the JSON string and the object type of the JSON string to be converted.

package org.kodejava.example.google.gson;

import com.google.gson.Gson;

public class JSONToStudent {
    public static void main(String[] args) {
        String json = "{" +
                "'name' : 'Duke'," +
                "'address' : 'Menlo Park'," +
                "'dateOfBirth' : 'Feb 1, 2000 12:00:00 AM'" +
                "}";

        Gson gson = new Gson();
        Student student = gson.fromJson(json, Student.class);

        System.out.println("s.getName()        = " + student.getName());
        System.out.println("s.getAddress()     = " + student.getAddress());
        System.out.println("s.getDateOfBirth() = " + student.getDateOfBirth());
    }
}

This example will print the following result:

s.getName()        = Duke
s.getAddress()     = Menlo Park
s.getDateOfBirth() = Tue Feb 01 00:00:00 WITA 2000

You can find the Student class on the previous example, How do I convert object into JSON?.

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.2</version>
</dependency>

How do I convert object into JSON?

In this example we are using Google Gson to convert an object (Student object) into JSON notation. Practically we can use this library to convert any object in Java and it is quite simple. You just need to create an instance of Gson class and then call the .toJson() method and pass the object to be converted into JSON string.

package org.kodejava.example.google.gson;

import com.google.gson.Gson;

import java.util.Calendar;

public class StudentToJson {
    public static void main(String[] args) {
        Calendar dob = Calendar.getInstance();
        dob.set(2000, 1, 1, 0, 0, 0);
        Student student = new Student("Duke", "Menlo Park", dob.getTime());

        Gson gson = new Gson();
        String json = gson.toJson(student);
        System.out.println("json = " + json);
    }
}

When you run the example above you’ll get an output like:

json = {"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}

Below is our Student class.

package org.kodejava.example.google.gson;

import java.io.Serializable;
import java.util.Date;

public class Student implements Serializable {
    private String name;
    private String address;
    private Date dateOfBirth;

    public Student() {
    }

    public Student(String name, String address, Date dateOfBirth) {
        this.name = name;
        this.address = address;
        this.dateOfBirth = dateOfBirth;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
}

Maven Dependencies


<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.2</version>
</dependency>

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 folder or from inside a jar file.

package org.kodejava.example.io;

import java.io.*;

public class StreamToString {

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

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

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

    public String convertStreamToString(InputStream is) 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 (is != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(
                        new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        }
        return "";
    }
}

How do I convert string of time to time object?

You want to convert a string representing a time into a time object in Java. As we know that Java represents a time information in a class java.util.Date, this class keep information for date and time.

Now if you have a string of time like 15:30:18, you can use a SimpleDateFormat object to parse the string time and return a java.util.Date object. The pattern of the string should be passed to the SimpleDateFormat constructor. In the example below the string is formatted as hh:mm:ss (hour:minute:second).

package org.kodejava.example.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToTimeExample {
    public static void main(String[] args) {        
        // A string of time information
        String time = "15:30:18";

        // Create an instance of SimpleDateFormat with the specified
        // format.
        DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
        try {
            // To get the date object from the string just called the 
            // parse method and pass the time string to it. This method 
            // throws ParseException if the time string is invalid. 
            // But remember as we don't pass the date information this 
            // date object will represent the 1st of january 1970.
            Date date = sdf.parse(time);            
            System.out.println("Date and Time: " + date);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How do I convert Date to String?

package org.kodejava.example.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateToString {
    public static void main(String[] args) {
        // Create an instance of SimpleDateFormat used for formatting 
        // the string representation of date (month/day/year)
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

        // Get the date today using Calendar object.
        Date today = Calendar.getInstance().getTime();        
        // Using DateFormat format method we can create a string 
        // representation of a date with the defined format.
        String reportDate = df.format(today);

        // Print what date is today!
        System.out.println("Report Date: " + reportDate);
    }
}

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 an 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.example.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.example.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 number 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.example.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?

package org.kodejava.example.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);
        }

        String s = "false";

        // 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
        Boolean bools = Boolean.valueOf(s);
        System.out.println("bools = " + bools);

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