Java examples for java.util:Date Parse
Parse the string date in the form of MMyyyy and return a Date object to represent an end date
//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; /**/* w w w . j a v a 2s.c o m*/ * Parse the string date in the form of MMyyyy and return a Date object to * represent an end date * * @param endDate * A string in the form of MMyyyy representing the end date for * desired data * @return Date A date object set to the first day of the following month * @throws ParseException * throws ParseException if the date can not be parsed. */ public static Date getEndDate(final String endDate) throws ParseException { Date toDate = parseDate(endDate); Calendar cal = Calendar.getInstance(); cal.setTime(toDate); cal.add(Calendar.MONTH, 1); return cal.getTime(); } /** * 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; } }