Search code examples
javaparsingtimedoubledatetime-conversion

Convert Double to java.sql.Time


I am reading data from a cell in Excel file. I have the value of time(milliseconds) in Double i.e. 0.36712962962962964.

I need to convert this value to java.sql.Time format. I tried parsing it using various approaches but it fails. Following is the code.

timeInDouble = 0.36712962962962964; Time time = new Time(Long.parseLong(timeInDouble.toString()));

The output for this code is:

java.lang.NumberFormatException: For input string: "0.36712962962962964"

What is the correct way for this conversion?


Solution

  • The double value represents a part of day duration, where 0 is begin and 1 is the end of the day. Contructor of Time class expects the time in milliseconds. In a day there are 24 x 60 x 60 x 1000 milliseconds. First we convert daouble into the number of milliseconds since the beginning of the day. Then create a time using milliseconds.

    double timeInDouble = 0.36712962962962964;
    
    // The number of milliseconds since the beginning of the day
    long milliseconds = (long) (timeInDouble * 24 * 60 * 60 * 1000);
    
    Time time = new Time(milliseconds);