Costumize android Fecha como twitter y feed de noticias de instagram

¿cómo puedo personalizar el formato de fecha en un desarrollo de Android para ser como el de twitter e instagram. Lo que tengo debajo de mi código actual, pero no me gusta el formato que produce como "hace 11 minutos" o "hace 34 minutos". Prefiero el formato twitter como "11m" o "34m". Por favor, nadie sabe cómo puedo dar formato a mi fecha de esa manera? Gracias

Date createdAt = message.getCreatedAt();//get the date the message was created from parse backend long now = new Date().getTime();//get current date String convertedDate = DateUtils.getRelativeTimeSpanString( createdAt.getTime(), now, DateUtils.SECOND_IN_MILLIS).toString(); mPostMessageTimeLabel.setText(convertedDate); //sets the converted date into the message_item.xml view 

Puedo ser un poco tarde, pero lo escribo para alguien que está buscando una solución. Utilizando PrettyTime puede obtener fechas con formato como "hace 2 meses" y así sucesivamente. Para adaptarse a sus necesidades tiene que alimentarlo con un objeto TimeFormat personalizado, no hay necesidad de crear un nuevo objeto TimeUnit ya que estamos formateando unidades de tiempo normales. Para ello, sólo tiene que crear su objeto TimeFormat para minutos, por ejemplo:

 public class CustomMinuteTimeFormat implements TimeFormat { @Override public String format(Duration duration) { return Math.abs(duration.getQuantity()) + "m"; } @Override public String formatUnrounded(Duration duration) { return format(duration); } @Override public String decorate(Duration duration, String time) { return time; } @Override public String decorateUnrounded(Duration duration, String time) { return time; } } 

Instantiate una nueva instancia de PrettyTime y configura tu formateador.

 PrettyTime pretty = new PrettyTime(); //This line of code is very important pretty.registerUnit(new Minute(), new CustomMinuteTimeFormat()); //Use your PrettyTime object as usual pretty.format(yourDateObject); 

Esto emitirá "2m" si el tiempo transcurrido es de 2 minutos.

Tenía el mismo problema. En lugar de usar una biblioteca pensé que probablemente podría escribir mi propia versión y que sea un poco más comprensible en cuanto a lo que está sucediendo (y ser capaz de ajustar un poco si es necesario).

Aquí está el método de la utilidad que hice (declaraciones útiles del Log para que los usuarios de Androide la proben hacia fuera incluidas):

 public static String convertLongDateToAgoString (Long createdDate, Long timeNow){ Long timeElapsed = timeNow - createdDate; // For logging in Android for testing purposes /* Date dateCreatedFriendly = new Date(createdDate); Log.d("MicroR", "dateCreatedFriendly: " + dateCreatedFriendly.toString()); Log.d("MicroR", "timeNow: " + timeNow.toString()); Log.d("MicroR", "timeElapsed: " + timeElapsed.toString());*/ // Lengths of respective time durations in Long format. Long oneMin = 60000L; Long oneHour = 3600000L; Long oneDay = 86400000L; Long oneWeek = 604800000L; String finalString = "0sec"; String unit; if (timeElapsed < oneMin){ // Convert milliseconds to seconds. double seconds = (double) ((timeElapsed / 1000)); // Round up seconds = Math.round(seconds); // Generate the friendly unit of the ago time if (seconds == 1) { unit = "sec"; } else { unit = "secs"; } finalString = String.format("%.0f", seconds) + unit; } else if (timeElapsed < oneHour) { double minutes = (double) ((timeElapsed / 1000) / 60); minutes = Math.round(minutes); if (minutes == 1) { unit = "min"; } else { unit = "mins"; } finalString = String.format("%.0f", minutes) + unit; } else if (timeElapsed < oneDay) { double hours = (double) ((timeElapsed / 1000) / 60 / 60); hours = Math.round(hours); if (hours == 1) { unit = "hr"; } else { unit = "hrs"; } finalString = String.format("%.0f", hours) + unit; } else if (timeElapsed < oneWeek) { double days = (double) ((timeElapsed / 1000) / 60 / 60 / 24); days = Math.round(days); if (days == 1) { unit = "day"; } else { unit = "days"; } finalString = String.format("%.0f", days) + unit; } else if (timeElapsed > oneWeek) { double weeks = (double) ((timeElapsed / 1000) / 60 / 60 / 24 / 7); weeks = Math.round(weeks); if (weeks == 1) { unit = "week"; } else { unit = "weeks"; } finalString = String.format("%.0f", weeks) + unit; } return finalString; } 

Uso:

 Long createdDate = 1453394736888L; // Your Long Long timeNow = new Date().getTime(); Log.d("MicroR", convertLongDateToAgoString(createdDate, timeNow)); // Outputs: // 1min // 3weeks // 5hrs // etc. 

¡Siéntete libre de probar esto y déjame saber si encuentras algún problema!

  • Get Value Of Day Month forma objeto de la fecha en Android?
  • ¿Cómo puedo obtener la fecha actual en Android?
  • SimpleDateFormat toma demasiado tiempo cuando se incluye la zona horaria
  • Problema con el análisis Fecha cadena:
  • SimpleDateFormat devuelve la fecha de la cadena en diferentes idiomas
  • ¿Por qué este análisis de SimpleDataFormat falla en Android?
  • SimpleDateFormat 24h
  • Android.text.format.DateFormat "HH" no se reconoce como con java.text.SimpleDateFormat
  • SimpleDateFormat: excepción de fecha incomparable
  • Objeto de fecha SimpleDateFormat no analiza correctamente la cadena de hora en el entorno Java (Android)
  • Formato de una cadena de fecha y hora sólo
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.