Parse the string date in the form of MMyyyy and return a Date object - Java java.util

Java examples for java.util:Date Parse

Description

Parse the string date in the form of MMyyyy and return a Date object

Demo Code


//package com.java2s;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    private static final int DATE_LENGTH = 6;

    /**//from   w  ww . j a  v  a 2s .c o m
     * Parse the string date in the form of MMyyyy and return a Date object
     *
     * @param startDate
     *            A string in the form of MMyyyy representing a start date for
     *            desired data
     * @return Date A date representation of that month and year, with day of
     *         month being the first
     * @throws ParseException
     *             throws ParseException if the date can not be parsed.
     */
    public static Date getStartDate(final String startDate)
            throws ParseException {
        return parseDate(startDate);

    }

    /**
     * This method parse the string date in the form of MMyyyy and return a
     * java.util.Date object
     * @param date
     *            A string in the form of MMyyyy representing date
     * @return Date A Date object in the form of MMyyyy
     * @throws ParseException
     *             throws ParseException if the date can not be parsed.
     */
    public static Date parseDate(final String date) throws ParseException {
        String date1;
        Date current = Calendar.getInstance().getTime();
        SimpleDateFormat dateformat = new SimpleDateFormat("MMyyyy");
        dateformat.setLenient(false);
        if (date == null) {
            date1 = dateformat.format(current);
        } else {
            date1 = date;
        }
        ParsePosition parsePosition = new ParsePosition(0);
        Date newDate = dateformat.parse(date1, parsePosition);
        // validation for extra characters in date string
        if (parsePosition.getIndex() != date1.length()
                || date1.length() > DATE_LENGTH) {
            throw new ParseException(
                    "Invalid date, expected format MMyyyy",
                    parsePosition.getIndex());
        }
        return newDate;
    }
}

Related Tutorials