Java Date Format As getDateYYYYMMDD(Object yyyymmdd)

Here you can find the source of getDateYYYYMMDD(Object yyyymmdd)

Description

Helper parsing two kinds of dates:
1.

License

MIT License

Parameter

Parameter Description
yyyymmdd a parameter

Exception

Parameter Description
ParseException an exception

Return

Date

Declaration

public static Date getDateYYYYMMDD(Object yyyymmdd) throws ParseException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 *  Copyright ? 2012-2015 eBay Software Foundation
 *  This program is dual licensed under the MIT and Apache 2.0 licenses.
 *  Please see LICENSE for more information.
 *******************************************************************************/

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

public class Main {
    private static final SimpleDateFormat[] s_formatsYMD = { new SimpleDateFormat("yyyy-MM-dd"),
            new SimpleDateFormat("yyyy-MM") };

    /**/*from w  w  w. j a  v  a 2  s. com*/
     * Helper parsing two kinds of dates:<br>
     * 1. YYYY-MM-DD -> returns 00:00:00 (midnight) of this day <br>
     * 2. YYYY-MM -> returns 23:59:59 of THE LAST DAY of this month - this is for credit card expirations<br>
     * 
     * @param yyyymmdd
     * @return Date
     * @throws ParseException
     */
    public static Date getDateYYYYMMDD(Object yyyymmdd) throws ParseException {
        if (yyyymmdd == null)
            return null;
        String sdate = yyyymmdd.toString();
        if (sdate.lastIndexOf('-') > sdate.indexOf('-')) {
            SimpleDateFormat formatter = s_formatsYMD[0];
            synchronized (formatter) { // yes, it's better: see comment in getDateFromISO8601
                return formatter.parse(sdate);
            }
        }
        // otherwise we get the very last second credit card is valid at
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat formatter = s_formatsYMD[1];
        synchronized (formatter) { // yes, it's better: see comment in getDateFromISO8601
            calendar.setTime(formatter.parse(sdate));
        }
        int lastDay = calendar.getActualMaximum(Calendar.DATE);
        calendar.set(Calendar.DATE, lastDay);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }
}

Related

  1. getDateAsISO8601String(Date date)
  2. getDateAsISO8601String(Date date)
  3. getDateAsISOTimestampString(Date timestamp)
  4. getDateAsRFC822String(Date date)
  5. getDateYYYYMMDD()
  6. getDateYYYYMMDD_HHSSMMNNN()
  7. getDateYyyyMmWithoutDash()