Get the date from a calendar to a string. - Android java.util

Android examples for java.util:Month

Description

Get the date from a calendar to a string.

Demo Code


//package com.java2s;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Main {
    /**/*from w  w w  . j  av a2  s.  c o m*/
     * Get the date from a calendar to a string.
     * @param calendar The Calendar to convert.
     * @return The formatted date
     */
    public static String convertToDateString(GregorianCalendar calendar) {
        return convertToMonthString(calendar) + " "
                + convertToDayOfMonthString(calendar) + ", "
                + convertToYearString(calendar);
    }

    /**
     * Get the month from a calendar to a string.
     * @param calendar The Calendar to convert.
     * @return The formatted month.
     */
    public static String convertToMonthString(GregorianCalendar calendar) {
        // SimpleDateFormat should work here, but it throws an exception. I'm not sure why...
        // It's probably because SimpleDateFormat is expecting a Date object rather than a 
        // GregorianCalendar object.

        // Get the value for the month.
        int monthValue = calendar.get(Calendar.MONTH);

        switch (monthValue) {
        case Calendar.JANUARY:
            return "January";
        case Calendar.FEBRUARY:
            return "February";
        case Calendar.MARCH:
            return "March";
        case Calendar.APRIL:
            return "April";
        case Calendar.MAY:
            return "May";
        case Calendar.JUNE:
            return "June";
        case Calendar.JULY:
            return "July";
        case Calendar.AUGUST:
            return "August";
        case Calendar.SEPTEMBER:
            return "September";
        case Calendar.OCTOBER:
            return "October";
        case Calendar.NOVEMBER:
            return "November";
        case Calendar.DECEMBER:
            return "December";
        default:
            return "Invalid Month";
        }
    }

    /**
     * Get the day of the month from a calendar to a string.
     * @param calendar The Calendar to convert.
     * @return The formatted day of the month.
     */
    public static String convertToDayOfMonthString(
            GregorianCalendar calendar) {
        return Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
    }

    /**
     * Get the year from a calendar to a string.
     * @param calendar The Calendar to convert.
     * @return The formatted year.
     */
    public static String convertToYearString(GregorianCalendar calendar) {
        return Integer.toString(calendar.get(Calendar.YEAR));
    }
}

Related Tutorials