Parse a date/time string of the specified format into a Calendar object - Android java.util

Android examples for java.util:Time

Description

Parse a date/time string of the specified format into a Calendar object

Demo Code


import android.util.Log;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class Main{
    private static final String TAG = TimeUtils.class.getName();
    /**/*w w w  . j a  v  a 2 s  .  c om*/
     * Parse a date/time string of the specified format into a Calendar object
     *
     * @param timeString string to be parsed
     * @param format format of string to be parsed
     * @return a Calendar based on parsed string
     */
    public static Calendar parseStringToCalendar(String timeString,
            String format) {
        return dateToCalendar(parseStringToDate(timeString, format));
    }
    /**
     * Converts a Date to a Calendar
     *
     * @param date date to convert
     * @return a calendar
     */
    public static Calendar dateToCalendar(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(date.getTime());
        cal.setTimeZone(TimeZone.getDefault());
        return cal;
    }
    /**
     * Parse a date/time string of the specified format into a Date object
     *
     * @param timeString string to be parsed
     * @param format format of string to be parsed
     * @return a Date based on parsed string
     */
    public static Date parseStringToDate(String timeString, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
        try {
            return sdf.parse(timeString);
        } catch (ParseException e) {
            Log.e(TAG, "Could not parse date string", e);
            return null;
        }

    }
}

Related Tutorials