Java Timestamp doubleToTimestamp(double f)

Here you can find the source of doubleToTimestamp(double f)

Description

double To Timestamp

License

Apache License

Declaration

public static Timestamp doubleToTimestamp(double f) 

Method Source Code

//package com.java2s;
/**/*  ww  w .ja  v a  2  s .c o m*/
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.math.BigDecimal;
import java.sql.Timestamp;

public class Main {
    public static Timestamp doubleToTimestamp(double f) {
        try {
            long seconds = (long) f;

            // We must ensure the exactness of the double's fractional portion.
            // 0.6 as the fraction part will be converted to 0.59999... and
            // significantly reduce the savings from binary serialization
            BigDecimal bd = new BigDecimal(String.valueOf(f));

            bd = bd.subtract(new BigDecimal(seconds)).multiply(new BigDecimal(1000000000));
            int nanos = bd.intValue();

            // Convert to millis
            long millis = seconds * 1000;
            if (nanos < 0) {
                millis -= 1000;
                nanos += 1000000000;
            }
            Timestamp t = new Timestamp(millis);

            // Set remaining fractional portion to nanos
            t.setNanos(nanos);
            return t;
        } catch (NumberFormatException nfe) {
            return null;
        } catch (IllegalArgumentException iae) {
            return null;
        }
    }
}

Related

  1. dateToOracleStr(java.sql.Timestamp ts)
  2. dayNumber(Timestamp stamp)
  3. daysBetween(Timestamp t1, Timestamp t2)
  4. delta_hours(Timestamp startdate, Timestamp enddate)
  5. differDayByNow(Timestamp timestamp)
  6. durationBetween(Timestamp startedAt, Timestamp completedAt)
  7. encodeTimestamp(Timestamp timestamp)
  8. endOfMonth(java.sql.Timestamp dd)
  9. extractDateSystemTimeStamp()