All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.clickzetta.platform.util.TimestampUtil Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
package com.clickzetta.platform.util;


import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class TimestampUtil {

  private TimestampUtil() {
  }

  private static final ThreadLocal DATE_FORMAT = new ThreadLocal() {
    @Override
    protected DateFormat initialValue() {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
      sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
      return sdf;
    }
  };

  public static long timestampToSec(Timestamp timestamp) {
    long second = timestamp.getTime() / 1000L;
    return second;
  }

  public static long timestampToMillis(Timestamp timestamp) {
    return timestamp.getTime();
  }

  public static long timestampToMicros(Timestamp timestamp) {
    long millis = timestamp.getTime() * 1000L;
    long micros = (timestamp.getNanos() % 1000000L) / 1000L;
    if (micros >= 0) {
      return millis + micros;
    } else {
      return millis + 1000000L + micros;
    }
  }

  public static long timestampToNano(Timestamp timestamp) {
    return timestamp.getNanos();
  }

  public static Timestamp microsToTimestamp(long micros) {
    long millis = micros / 1000L;
    long nanos = (micros % 1000000L) * 1000L;
    if (nanos < 0) {
      millis -= 1L;
      nanos += 1000000000L;
    }
    Timestamp timestamp = new Timestamp(millis);
    timestamp.setNanos((int) nanos);
    return timestamp;
  }

  public static String timestampToString(Timestamp timestamp) {
    long micros = timestampToMicros(timestamp);
    return timestampToString(micros);
  }

  public static String timestampToString(long micros) {
    long tsMillis = micros / 1000L;
    long tsMicros = micros % 1000000L;
    String tsStr = DATE_FORMAT.get().format(new Date(tsMillis));
    return String.format("%s.%06dZ", tsStr, tsMicros);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy