Java Timestamp Create toTimeStamp(Date date, String time)

Here you can find the source of toTimeStamp(Date date, String time)

Description

to Time Stamp

License

Open Source License

Declaration

public static Timestamp toTimeStamp(Date date, String time) 

Method Source Code


//package com.java2s;
import java.sql.Timestamp;

import java.util.Calendar;
import java.util.Date;

public class Main {
    public static Timestamp toTimeStamp(Date date, String time) {
        Calendar cal = Calendar.getInstance();
        cal.setLenient(true);//from  w  w w. j  a va  2s.c o m
        boolean formatIs12 = time.endsWith("PM") || time.endsWith("AM");

        String[] hhmmss = time.split(":");
        if (hhmmss.length < 2)
            throw new IllegalArgumentException("invalid time");

        if (hhmmss.length == 2) {
            String[] newTime = new String[3];
            newTime[0] = hhmmss[0];
            String[] temp = hhmmss[1].split(" ");
            newTime[1] = temp[0];
            newTime[2] = "00";
            if (formatIs12)
                newTime[2] += " " + temp[1];

            hhmmss = newTime;
        }
        int hh = Integer.parseInt(hhmmss[0]);

        if (formatIs12 && time.endsWith("PM") && hh != 12)
            hh += 12;

        cal.set(Calendar.HOUR_OF_DAY, hh);

        cal.set(Calendar.MINUTE, Integer.parseInt(hhmmss[1]));

        if (hhmmss.length == 3) {
            String ss = hhmmss[2];
            if (formatIs12)
                ss = ss.split(" ")[0];

            cal.set(Calendar.SECOND, Integer.parseInt(ss));
        }
        cal.set(Calendar.MILLISECOND, 0);

        return new Timestamp(cal.getTimeInMillis());
    }
}

Related

  1. toSQLTimestamp(String time)
  2. toTimestamp(BigDecimal value)
  3. toTimestamp(Date date)
  4. toTimestamp(Date date)
  5. toTimestamp(Date date)
  6. toTimestamp(DateTime dt)
  7. toTimestamp(final Calendar cal)
  8. toTimestamp(final Instant instant)
  9. toTimestamp(final int year, final int month, final int dayOfMonth, final int hour, final int minute, final int second, final int millsecond)