Java Timestamp Parse parseTimestamp(final String s)

Here you can find the source of parseTimestamp(final String s)

Description

parse Timestamp

License

Apache License

Declaration

@SuppressWarnings("deprecation")
    public static java.sql.Timestamp parseTimestamp(final String s) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.util.Date;

public class Main {
    @SuppressWarnings("deprecation")
    public static java.sql.Timestamp parseTimestamp(final String s) {
        final String[] components = s.split(" ");
        if (components.length != 2) {
            throw new IllegalArgumentException("Invalid escape format: " + s);
        }//  w  w w.j  a  v  a2 s.c  om

        final String[] timeComponents = components[1].split("\\.");
        if (timeComponents.length != 2) {
            throw new IllegalArgumentException("Invalid escape format: " + s);
        } else if (timeComponents[1].length() != 9) {
            throw new IllegalArgumentException("Invalid escape format: " + s);
        }

        final String[] dSplit = components[0].split("-");
        final String[] tSplit = timeComponents[0].split(":");
        if (dSplit.length != 3 || tSplit.length != 3) {
            throw new IllegalArgumentException("Invalid escape format: " + s);
        }
        trimLeading0(dSplit);
        trimLeading0(tSplit);

        if (timeComponents[1].startsWith("0")) {
            timeComponents[1] = timeComponents[1].replaceFirst("^00*", "");
            if (timeComponents[1].length() == 0) {
                timeComponents[1] = "0";
            }
        }

        try {
            int yy = Integer.parseInt(dSplit[0]) - 1900;
            int mm = Integer.parseInt(dSplit[1]) - 1;
            int dd = Integer.parseInt(dSplit[2]);

            int hh = Integer.parseInt(tSplit[0]);
            int mi = Integer.parseInt(tSplit[1]);
            int ss = Integer.parseInt(tSplit[2]);
            int ms = Integer.valueOf(timeComponents[1]) / 1000000;

            return new java.sql.Timestamp(Date.UTC(yy, mm, dd, hh, mi, ss) + ms);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid escape format: " + s);
        }
    }

    private static void trimLeading0(final String[] dSplit) {
        for (int i = 0; i < 3; i++) {
            if (dSplit[i].startsWith("0")) {
                dSplit[i] = dSplit[i].substring(1);
            }
        }
    }
}

Related

  1. parseSQLiteTimestamp(String dd)
  2. parseStopTime(String timestamp, String timezone)
  3. parseTimestamp(Date date)
  4. parseTimestamp(Date date)
  5. parseTimestamp(final String format, final String time)
  6. parseTimeStamp(final String... key)
  7. parseTimestamp(Long time, String pattern)
  8. parseTimestamp(Object o)
  9. parseTimestamp(String d)