Java Parse Date parseDate(String date)

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

Description

Try parse a Date from a String with 2 different formats, otherwise return null

License

Open Source License

Parameter

Parameter Description
date - The String with the date to be parsed

Return

- A Date if the String had the right format, otherwise null

Declaration

public static Calendar parseDate(String date) 

Method Source Code


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

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

public class Main {
    /**// w w  w  .j av  a 2 s  .  c o m
     * Try parse a Date from a String with 2 different formats, otherwise return null
     *
     * @param date - The String with the date to be parsed
     * @return - A Date if the String had the right format, otherwise null
     */
    public static Calendar parseDate(String date) {
        if (date == null || date.equals("null")) {
            return null;
        }
        List<SimpleDateFormat> dateFormats = new ArrayList<SimpleDateFormat>();
        dateFormats.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        Date d = new Date();
        for (SimpleDateFormat format : dateFormats) {
            try {
                d = format.parse(date);
                break;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        Calendar c = new GregorianCalendar();
        c.setTime(d);
        System.out.println("RETURNING CALENDAR: " + c);
        return c;
    }

    public static String parseDate(Calendar date) {
        if (date == null) {
            return "null";
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("TIME IN MILLIS: " + date.getTime());
        String d = format.format(date.getTime());
        return d;
    }
}

Related

  1. parseDate(String currDate)
  2. parseDate(String d)
  3. parseDate(String d)
  4. parseDate(String d)
  5. parseDate(String datastr, String pattern)
  6. parseDate(String date)
  7. parseDate(String date)
  8. parseDate(String date)
  9. parseDate(String date)