Java String to Date stringToDate(String date)

Here you can find the source of stringToDate(String date)

Description

Formats a date given as a string in a stringobject allowed dates are

"yyyy/MM/dd HH:mm" "yyyy-MM-dd HH:mm" "yyyy/MM/dd" "yyyy-MM-dd"

License

Open Source License

Parameter

Parameter Description
date to convert

Return

date object

Declaration

public static Date stringToDate(String date) throws ParseException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    /**//from   w ww  .j a v  a  2 s  .  co  m
     * Formats a date given as a string in a stringobject
     * allowed dates are
     * <p/>
     * "yyyy/MM/dd HH:mm"
     * "yyyy-MM-dd HH:mm"
     * "yyyy/MM/dd"
     * "yyyy-MM-dd"
     *
     * @param date to convert
     * @return date object
     */
    public static Date stringToDate(String date) throws ParseException {
        String pattern;
        if (date.contains("/") && date.contains(":")) {
            pattern = "yyyy/MM/dd HH:mm";
        } else if (date.contains("/") && !date.contains(":")) {
            pattern = "yyyy/MM/dd";
        } else if (date.contains("-") && date.contains(":")) {
            pattern = "yyyy-MM-dd HH:mm";
        } else if (date.contains("-") && !date.contains(":")) {
            pattern = "yyyy-MM-dd";
        } else {
            pattern = "dd.mm.yyyy";
        }

        return new SimpleDateFormat(pattern).parse(date);
    }
}

Related

  1. stringToDate(final String dateTimeStr)
  2. stringToDate(final String str, final String dateFormat)
  3. stringToDate(final String string, final String format)
  4. StringToDate(String data)
  5. stringToDate(String data)
  6. stringToDate(String date)
  7. stringToDate(String date)
  8. stringToDate(String date)
  9. stringToDate(String date)