Android Calendar to String Convert toHumanDate(Calendar cal)

Here you can find the source of toHumanDate(Calendar cal)

Description

Formats a calendar instance to relative timestamp.

License

MIT License

Parameter

Parameter Description
cal The input date

Return

A formatted duration string

Declaration

public static String toHumanDate(Calendar cal) 

Method Source Code

//package com.java2s;
/**/*  www .  j  a  v a 2 s .  c o  m*/
 *   DateTimeUtils.java
 *
 *  A utility class for converting dates to common formats
 *
 *   @author Robin Andersson, Johan Brook
 *   @copyright (c) 2012 Robin Andersson, Johan Brook, Mattias Henriksson, Lisa Stenberg
 *   @license MIT
 */

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

public class Main {
    /**
     * Formats a calendar instance to relative timestamp.
     * 
     * <p>
     * Such as "next year", "3 days", etc. Only works for future dates.
     * </p>
     * 
     * @param cal
     *            The input date
     * @return A formatted duration string
     */
    public static String toHumanDate(Calendar cal) {
        Calendar now = GregorianCalendar.getInstance();

        int years = cal.get(Calendar.YEAR) - now.get(Calendar.YEAR);
        int months = cal.get(Calendar.MONTH) - now.get(Calendar.MONTH);
        int days = cal.get(Calendar.DAY_OF_MONTH)
                - now.get(Calendar.DAY_OF_MONTH);

        if (years == 1)
            return "next year";
        else if (years > 1)
            return years + " years";
        else if (months == 1)
            return "next month";
        else if (months > 1)
            return months + " months";
        else if (days == 1)
            return "tomorrow";
        else if (days > 1)
            return days + " days";

        return "today";
    }
}

Related

  1. convertToDateStamp(Calendar cal)
  2. toSimpleDate(Calendar calendar)
  3. calendarToString(Calendar date)