Given a String representing a date, parses yyyy-MM-dd and returns a Calendar object representing the date. - Java java.util

Java examples for java.util:Date Parse

Description

Given a String representing a date, parses yyyy-MM-dd and returns a Calendar object representing the date.

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        String dateString = "java2s.com";
        System.out.println(parseDate(dateString));
    }/* w ww.  j a v a2s .co  m*/

    /**
     * Given a String representing a date, parses and returns a Calendar object
     * representing the date.
     * 
     * @param dateString - the date as a String in yyyy-MM-dd format (e.g., 2014-05-14)
     * @return a Calendar representing dateString
     */
    public static Calendar parseDate(String dateString) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        GregorianCalendar gc = new GregorianCalendar();
        try {
            gc.setTime(formatter.parse(dateString));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return gc;
    }
}

Related Tutorials