Convert string as format "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd HH:mm" or "yyyy-MM-dd" to java.util.Date. - Java java.util

Java examples for java.util:Time

Description

Convert string as format "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd HH:mm" or "yyyy-MM-dd" to java.util.Date.

Demo Code


//package com.java2s;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Main {
    /**/*from  www.ja  va 2 s. c om*/
     * Convert string as format "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd HH:mm" or "yyyy-MM-dd" to java.util.Date.
     * 
     * @param date String date.
     * @return java.util.Date object.
     */
    public static java.util.Date asUtilDate(String date) {
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
        } catch (ParseException e) {
        }
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(date);
        } catch (ParseException e) {
        }
        try {
            return new SimpleDateFormat("yyyy-MM-dd").parse(date);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

Related Tutorials