Convert a String representation of a date from the database or preferences to a Date object - Android java.util

Android examples for java.util:Date Format

Description

Convert a String representation of a date from the database or preferences to a Date object

Demo Code

import android.content.Context;
import android.util.Log;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

public class Main{

    /**//from  ww  w.jav a 2 s .  c  o  m
     * Convert a String representation of a date from the database or preferences to a Java Date
     * object.
     * @param date A {@link String} representation of a date.
     * @return A {@link java.util.Date} object corresponding to that date.
     */
    public static Date convertDate(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
        Date dateValue;
        try {
            dateValue = sdf.parse(date);
        } catch (ParseException e) {
            // Date parsing failed, but this is so unexpected, that it should not break down.
            dateValue = new Date();
            Log.e(TAG, "Conversion of String date to Date Object failed.");
        }
        return dateValue;
    }
    /**
     * Convert a Java Date object to a String representation that is formatted for use in the
     * database or preferences.
     * @param date A {@link java.util.Date} object.
     * @return A {@link String} representation of that date.
     */
    public static String convertDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
        return sdf.format(date);
    }

}

Related Tutorials