Java String to Date stringToDate(String str, String format)

Here you can find the source of stringToDate(String str, String format)

Description

string To Date

License

Open Source License

Declaration

public static Date stringToDate(String str, String format) 

Method Source Code


//package com.java2s;

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

public class Main {

    public static Date stringToDate(String date) {
        if (date == null)
            return null;
        String[] temp = date.split("-");
        if (temp.length != 3)
            return null;
        Calendar instance = Calendar.getInstance();
        String[] temp1 = temp[2].split(" ");
        String dd = temp1[0];/*from ww  w. j av  a  2  s  .c  om*/
        String time = temp1[1];
        String[] temp2 = time.split(":");
        instance.set(Integer.parseInt(temp[0]), Integer.parseInt(temp[1]) - 1, Integer.parseInt(dd),
                Integer.parseInt(temp2[0]), Integer.parseInt(temp2[1]), Integer.parseInt(temp2[2]));
        return instance.getTime();
    }

    public static Date stringToDate(String date, boolean flag) {
        if (date == null)
            return null;
        String[] temp = date.split("-");
        if (temp.length != 3)
            return null;
        Calendar instance = Calendar.getInstance();
        if (flag) {
            instance.set(Integer.parseInt(temp[0]), Integer.parseInt(temp[1]) - 1, Integer.parseInt(temp[2]), 0, 0,
                    0);
        } else {
            instance.set(Integer.parseInt(temp[0]), Integer.parseInt(temp[1]) - 1, Integer.parseInt(temp[2]), 23,
                    59, 59);
        }
        return instance.getTime();
    }

    public static Date stringToDate(String str, String format) {
        if (str != null) {
            DateFormat dateFormat = new SimpleDateFormat(format);
            try {
                return dateFormat.parse(str);
            } catch (ParseException e) {
                return null;
            }
        }

        return null;
    }
}

Related

  1. stringToDate(String source)
  2. stringToDate(String source, String format)
  3. stringToDate(String str)
  4. StringToDate(String str)
  5. StringToDate(String str, String format)
  6. stringToDate(String str, String formatStr)
  7. stringToDate(String strDate)
  8. stringToDate(String strDate)
  9. stringToDate(String strDate)