Convert date to yesterday, today or tomorrow - Android java.util

Android examples for java.util:Date Time

Description

Convert date to yesterday, today or tomorrow

Demo Code

import android.text.TextUtils;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{
  private static SimpleDateFormat yyyy_MM_dd_HH_mm = new SimpleDateFormat(
      "yyyy-MM-dd HH:mm", Locale.getDefault());
  private static SimpleDateFormat HHmm = new SimpleDateFormat("HH:mm",
      Locale.getDefault());/*from w  w  w .  j a  v  a  2s .  co m*/
  private static SimpleDateFormat MM_dd_HHmm = new SimpleDateFormat(
      "MM-dd HH:mm", Locale.getDefault());
    public static String date2DayTime(Date oldTime) {
        Date newTime = new Date();
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(newTime);
            Calendar oldCal = Calendar.getInstance();
            oldCal.setTime(oldTime);

            int oldYear = oldCal.get(Calendar.YEAR);
            int year = cal.get(Calendar.YEAR);
            int oldDay = oldCal.get(Calendar.DAY_OF_YEAR);
            int day = cal.get(Calendar.DAY_OF_YEAR);

            if (oldYear == year) {
                int value = oldDay - day;
                if (value == -1) {
                    return "yesterday " + HHmm.format(oldTime);
                } else if (value == 0) {
                    return "today " + HHmm.format(oldTime);
                } else if (value == 1) {
                    return "tomorrow " + HHmm.format(oldTime);
                } else {
                    return MM_dd_HHmm.format(oldTime);
                }
            }
        } catch (Exception e) {

        }
        return yyyy_MM_dd_HH_mm.format(oldTime);
    }

}

Related Tutorials