Java SQL Time StrToDateTime(String val)

Here you can find the source of StrToDateTime(String val)

Description

Convert a string date in the YYYY-MM-DD HH:MM format into a java.util.Date object.

License

Open Source License

Parameter

Parameter Description
val The date string to be converted

Return

A date object matching the string sent in

Declaration

static public java.util.Date StrToDateTime(String val) 

Method Source Code


//package com.java2s;
import java.sql.*;
import java.util.Calendar;
import java.util.StringTokenizer;

public class Main {
    /**//  w  ww .j av a  2  s  .c  o  m
     * Convert a string date in the YYYY-MM-DD HH:MM format into a java.util.Date
     * object.
     *
     * @param val The date string to be converted
     * @return A date object matching the string sent in
     */
    static public java.util.Date StrToDateTime(String val) {
        Calendar cal = Calendar.getInstance();

        if (val != null) {
            StringTokenizer main = new StringTokenizer(val, " ");
            StringTokenizer st = new StringTokenizer(main.nextToken(), "-");

            // First grab the date
            cal.set(Calendar.YEAR, Integer.parseInt(st.nextToken()));
            cal.set(Calendar.MONTH, Integer.parseInt(st.nextToken()) - 1);
            cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(st.nextToken()));

            // Now grab the time
            StringTokenizer temptime = new StringTokenizer(main.nextToken(), ":");
            int hour = Integer.parseInt(temptime.nextToken());
            cal.set(Calendar.MINUTE, Integer.parseInt(temptime.nextToken()));

            if (main.hasMoreTokens()) {
                cal.set(Calendar.HOUR, hour);
                int merid = Calendar.AM;
                if (main.nextToken().equals("PM")) {
                    merid = Calendar.PM;
                }
                cal.set(Calendar.AM_PM, merid);
            } else {
                cal.set(Calendar.HOUR_OF_DAY, hour);
            }
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
        }
        return new Date(cal.getTimeInMillis());
    }
}

Related

  1. serializeSqlTime(Time time)
  2. setTime(PreparedStatement statement, int index, Date value)
  3. sqlDateTimeAdd(java.util.Date date, long milliseconds)
  4. sqlTime()
  5. str2dateTime(String handedate)
  6. strToTime(String strDate)
  7. toDate(TimeZone tz, int days)
  8. toDateFromTime(String time)
  9. todayBeginTime()