Java SQL Date Parse getSqlDateFromString(String dateAsString, String format)

Here you can find the source of getSqlDateFromString(String dateAsString, String format)

Description

converts a String to java.sql.Date

License

BSD License

Parameter

Parameter Description
dateAsString date in the form of a string
format format of the date string

Declaration

public static java.sql.Date getSqlDateFromString(String dateAsString, String format) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright Duke Comprehensive Cancer Center and SemanticBits
 * //from   w ww.ja  v a 2 s  .  c  om
 * Distributed under the OSI-approved BSD 3-Clause License.
 * See http://ncip.github.com/c3pr/LICENSE.txt for details.
 ******************************************************************************/

import java.util.StringTokenizer;

public class Main {
    public static final String DISPLAY_DATE_FORMAT = "MM/dd/yyyy";
    public static final String JDBC_DATE_ESCAPE_FORMAT = "yyyy-MM-dd";
    private static final String DISPLAY_DATE_DELIMITER = "/";
    private static final String JDBC_DATE_DELIMITER = "-";

    /**
     * converts a String to java.sql.Date
     * 
     * @param dateAsString
     *                date in the form of a string
     * @param format
     *                format of the date string
     * @rerurn date java.sql.Date, null if format is not one of the formats specified in DateUtil
     *         class
     */
    public static java.sql.Date getSqlDateFromString(String dateAsString, String format) {
        // date string of the form "mm/dd/yyyy"

        if (DISPLAY_DATE_FORMAT.equalsIgnoreCase(format)) {
            StringTokenizer dateAsTokens = new StringTokenizer(dateAsString, DISPLAY_DATE_DELIMITER);
            String month = dateAsTokens.nextToken();
            String date = dateAsTokens.nextToken();
            String year = dateAsTokens.nextToken();

            dateAsString = year + JDBC_DATE_DELIMITER + month + JDBC_DATE_DELIMITER + date;
            return java.sql.Date.valueOf(dateAsString);
        }
        // date string of the form "yyyy-mm-dd"
        else if (JDBC_DATE_ESCAPE_FORMAT.equalsIgnoreCase(format)) {
            return java.sql.Date.valueOf(dateAsString);
        }
        // default util.date to string convertion
        else {
            return null;
        }
    }
}

Related

  1. getSqlDate(String dateString, String format)
  2. getSqlDate(String str)
  3. getSqlDateByShortStr(String dateStr)
  4. getSqlDateFromStr(DateFormat format, String s, boolean need_default)
  5. getSQLDateFromStr(String s)
  6. parse(String date)
  7. parseDate(final String dateString)
  8. parseDate(String date)
  9. parseDate(String dateStr, String formatStr)