web-dev-qa-db-fra.com

Comment convertir le temps en "time ago" dans Android

Mon serveur C'est l'heure de retour: 

"2016-01-24T16:00:00.000Z"

Je voudrais 

1: convertir en chaîne.

2: Je veux le montrer "il y a du temps" quand le charger du serveur.

S'il vous plaît. Aidez moi!

15
anh thang Bui

Je vois principalement trois façons:

a) options intégrées utilisant SimpleDateFormat et DateUtils

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
long time = sdf.parse("2016-01-24T16:00:00.000Z").getTime();
long now = System.currentTimeMillis();

CharSequence ago = 
  DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS);

b) bibliothèque externe ocpsoft/PrettyTime (basé sur Java.util.Date)

Ici, vous devez également utiliser SimpleDateFormat pour produire le résultat time- en tant qu'interprétation de "2016-01-24T16: 00: 00.000Z".

PrettyTime prettyTime = new PrettyTime(Locale.getDefault());
String ago = prettyTime.format(new Date(time));

c) utiliser ma bibliothèque Time4A (poids lourd mais avec le meilleur support i18n)

Moment moment = Iso8601Format.EXTENDED_DATE_TIME_OFFSET.parse("2016-01-24T16:00:00.000Z");
String ago = PrettyTime.of(Locale.getDefault()).printRelativeInStdTimezone(moment);
18
Meno Hochschild

1 - créer un formateur de date:

public static final SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

2 - créer un objet Date

String dateStr = "2016-01-24T16:00:00.000Z";
Date date = inputFormat.parse(dateStr);

3 - Utilisez Android DateUtils pour créer une chaîne Nice Display:

String niceDateStr = DateUtils.getRelativeTimeSpanString(date.getTime() , Calendar.getInstance().getTimeInMillis(), DateUtils.MINUTE_IN_MILLIS);
12
Asaf Pinhassi

C'est très simple. Je vais vous dire avec mon code. 

package com.example;

import Java.text.SimpleDateFormat;
import Java.util.Date;
import Java.util.concurrent.TimeUnit;

public class TimeShow
{
    public static void main(String[] args) {
        try 
        {
            SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss");
            Date past = format.parse("2016.02.05 AD at 23:59:30");
            Date now = new Date();
            long seconds=TimeUnit.MILLISECONDS.toSeconds(now.getTime() - past.getTime());
            long minutes=TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime());
            long hours=TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime());
            long days=TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime());
//
//          System.out.println(TimeUnit.MILLISECONDS.toSeconds(now.getTime() - past.getTime()) + " milliseconds ago");
//          System.out.println(TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime()) + " minutes ago");
//          System.out.println(TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime()) + " hours ago");
//          System.out.println(TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime()) + " days ago");

            if(seconds<60)
            {
                System.out.println(seconds+" seconds ago");
            }
            else if(minutes<60)
            {
                System.out.println(minutes+" minutes ago");
            }
            else if(hours<24)
            {
                System.out.println(hours+" hours ago");
            }
            else 
            {
                System.out.println(days+" days ago");
            }
        }
        catch (Exception j){
            j.printStackTrace();
        }
    }
}
9

Sous Android, vous pouvez utiliser DateUtils.getRelativeTimeSpanString (long timeInMillis), en vous référant à https://developer.Android.com/reference/Android/text/format/DateUtils.html vous pouvez utiliser l'un des éléments suivants. variations de cette méthode pour la précision.

5
Marlon López

en utilisant le code @Excelso_Widi, j’ai pu vaincre,

J'ai modifié son code et également traduit en anglais.

public class TimeAgo2 {

public String covertTimeToText(String dataDate) {

    String convTime = null;

    String prefix = "";
    String suffix = "Ago";

    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        Date pasTime = dateFormat.parse(dataDate);

        Date nowTime = new Date();

        long dateDiff = nowTime.getTime() - pasTime.getTime();

        long second = TimeUnit.MILLISECONDS.toSeconds(dateDiff);
        long minute = TimeUnit.MILLISECONDS.toMinutes(dateDiff);
        long hour   = TimeUnit.MILLISECONDS.toHours(dateDiff);
        long day  = TimeUnit.MILLISECONDS.toDays(dateDiff);

        if (second < 60) {
            convTime = second+" Seconds "+suffix;
        } else if (minute < 60) {
            convTime = minute+" Minutes "+suffix;
        } else if (hour < 24) {
            convTime = hour+" Hours "+suffix;
        } else if (day >= 7) {
            if (day > 30) {
                convTime = (day / 30)+" Months "+suffix;
            } else if (day > 360) {
                convTime = (day / 360)+" Years "+suffix;
            } else {
                convTime = (day / 7) + " Week "+suffix;
            }
        } else if (day < 7) {
            convTime = day+" Days "+suffix;
        }

    } catch (ParseException e) {
        e.printStackTrace();
        Log.e("ConvTimeE", e.getMessage());
    }

    return convTime;

}

}

et je l'ai utilisé comme ça

 String time = jsonObject.getString("date_gmt");
 TimeAgo2 timeAgo2 = new TimeAgo2();
String MyFinalValue = timeAgo2.covertTimeToText(time);

Bon codage et merci @Excelso_Widi vous l'homme wink

4
The Dead Guy
private static final int SECOND_MILLIS = 1000;
private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
private static final int DAY_MILLIS = 24 * HOUR_MILLIS;

private static Date currentDate() {
    Calendar calendar = Calendar.getInstance();
    return calendar.getTime();
}

public static String getTimeAgo(Date date) {
    long time = date.getTime();
    if (time < 1000000000000L) {
        time *= 1000;
    }

    long now = currentDate().getTime();
    if (time > now || time <= 0) {
        return "in the future";
    }

    final long diff = now - time;
    if (diff < MINUTE_MILLIS) {
        return "moments ago";
    } else if (diff < 2 * MINUTE_MILLIS) {
        return "a minute ago";
    } else if (diff < 60 * MINUTE_MILLIS) {
        return diff / MINUTE_MILLIS + " minutes ago";
    } else if (diff < 2 * HOUR_MILLIS) {
        return "an hour ago";
    } else if (diff < 24 * HOUR_MILLIS) {
        return diff / HOUR_MILLIS + " hours ago";
    } else if (diff < 48 * HOUR_MILLIS) {
        return "yesterday";
    } else {
        return diff / DAY_MILLIS + " days ago";
    }
}

il suffit d'appeler getTimeAgo (timeInDate);

Cela fonctionne pour moi.

4
Kiran

Étape 1. Convertissez votre chaîne de temps au format milliseconde avec un type long

Étape 2. Utilisez le code ci-dessous

 private static final int SECOND_MILLIS = 1000; 
    private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS; 
    private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS; 
    private static final int DAY_MILLIS = 24 * HOUR_MILLIS; 

    public static String getTimeAgo(long time, Context ctx) { 
    if (time < 1000000000000L) { 
    //if timestamp given in seconds, convert to millis time *= 1000; } 
    long now = getCurrentTime(ctx); 
    if (time > now || time <= 0) { return null; } 
// TODO: localize final long diff = now - time; 
if (diff < MINUTE_MILLIS) { return "just now"; } 
    else if (diff < 2 * MINUTE_MILLIS) { return "a minute ago"; } 
    else if (diff < 50 * MINUTE_MILLIS) { return diff / MINUTE_MILLIS + " minutes ago"; } 
    else if (diff < 90 * MINUTE_MILLIS) { return "an hour ago"; } 
    else if (diff < 24 * HOUR_MILLIS) { return diff / HOUR_MILLIS + " hours ago"; } else if (diff < 48 * HOUR_MILLIS) { return "yesterday"; } 
    else { return diff / DAY_MILLIS + " days ago"; } }

// code ci-dessus de google!

3
GiapLee

Vous pouvez passer des millisecondes dans la méthode getlongtoago et obtenir une chaîne parfaitement formatée.

public static String getlongtoago(long createdAt) {
    DateFormat userDateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
    DateFormat dateFormatNeeded = new SimpleDateFormat("MM/dd/yyyy HH:MM:SS");
    Date date = null;
    date = new Date(createdAt);
    String crdate1 = dateFormatNeeded.format(date);

    // Date Calculation
    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    crdate1 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(date);

    // get current date time with Calendar()
    Calendar cal = Calendar.getInstance();
    String currenttime = dateFormat.format(cal.getTime());

    Date CreatedAt = null;
    Date current = null;
    try {
        CreatedAt = dateFormat.parse(crdate1);
        current = dateFormat.parse(currenttime);
    } catch (Java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Get msec from each, and subtract.
    long diff = current.getTime() - CreatedAt.getTime();
    long diffSeconds = diff / 1000;
    long diffMinutes = diff / (60 * 1000) % 60;
    long diffHours = diff / (60 * 60 * 1000) % 24;
    long diffDays = diff / (24 * 60 * 60 * 1000);

    String time = null;
    if (diffDays > 0) {
        if (diffDays == 1) {
            time = diffDays + "day ago ";
        } else {
            time = diffDays + "days ago ";
        }
    } else {
        if (diffHours > 0) {
            if (diffHours == 1) {
                time = diffHours + "hr ago";
            } else {
                time = diffHours + "hrs ago";
            }
        } else {
            if (diffMinutes > 0) {
                if (diffMinutes == 1) {
                    time = diffMinutes + "min ago";
                } else {
                    time = diffMinutes + "mins ago";
                }
            } else {
                if (diffSeconds > 0) {
                    time = diffSeconds + "secs ago";
                }
            }

        }

    }
    return time;
}
2
Pankaj Talaviya
public class TimeUtility {

public String covertTimeToText(String dataDate) {

    String convTime = null;

    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date pasTime = dateFormat.parse(dataDate);

        Date nowTime = new Date();

        long dateDiff = nowTime.getTime() - pasTime.getTime();

        long detik = TimeUnit.MILLISECONDS.toSeconds(dateDiff);
        long menit = TimeUnit.MILLISECONDS.toMinutes(dateDiff);
        long jam   = TimeUnit.MILLISECONDS.toHours(dateDiff);
        long hari  = TimeUnit.MILLISECONDS.toDays(dateDiff);

        if (detik < 60) {
            convTime = detik+"detik lalu";
        } else if (menit < 60) {
            convTime = menit+"menit lalu";
        } else if (jam < 24) {
            convTime = jam+"jam lalu";
        } else if (hari >= 7) {
            if (hari > 30) {
                convTime = (hari / 30)+"bulan lalu";
            } else if (hari > 360) {
                convTime = (hari / 360)+"tahun lalu";
            } else {
                convTime = (hari / 7) + "minggu lalu";
            }
        } else if (hari < 7) {
            convTime = hari+"hari lalu";
        }

    } catch (ParseException e) {
        e.printStackTrace();
        Log.e("ConvTimeE", e.getMessage());
    }

    return convTime;

  }

}
2
Excelso Widi

Ce que vous essayez de convertir est un format conforme à ISO 8601. Le moyen le plus simple de convertir cela consiste à utiliser Bibliothèque Joda-Time pour Android.

Une fois que vous avez ajouté cela à votre projet, vous pouvez utiliser ce code pour extraire la date exacte!

    DateTimeZone timeZone = DateTimeZone.getDefault();
    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd MMMM yyyy").withZone(timeZone);
    DateTime dateTime2 = new DateTime( isoDateToBeConverted, timeZone );
    String output = formatter.print( dateTime2 );
    Log.w("TIME IF WORKS::",""+output);

Aussi, voyez ceci pour formater la date dans votre choix préféré J'espère que cela vous aidera!

1
OBX

Version Kotlin 

private const val SECOND_MILLIS = 1000
private const val MINUTE_MILLIS = 60 * SECOND_MILLIS
private const val HOUR_MILLIS = 60 * MINUTE_MILLIS
private const val DAY_MILLIS = 24 * HOUR_MILLIS

private fun currentDate(): Date {
    val calendar = Calendar.getInstance()
    return calendar.time
}

fun getTimeAgo(date: Date): String {
    var time = date.time
    if (time < 1000000000000L) {
        time *= 1000
    }

    val now = currentDate().time
    if (time > now || time <= 0) {
        return "in the future"
    }

    val diff = now - time
    return when {
        diff < MINUTE_MILLIS -> "moments ago"
        diff < 2 * MINUTE_MILLIS -> "a minute ago"
        diff < 60 * MINUTE_MILLIS -> "${diff / MINUTE_MILLIS} minutes ago"
        diff < 2 * HOUR_MILLIS -> "an hour ago"
        diff < 24 * HOUR_MILLIS -> "${diff / HOUR_MILLIS} hours ago"
        diff < 48 * HOUR_MILLIS -> "yesterday"
        else -> "${diff / DAY_MILLIS} days ago"
    }
}
0
Kavin Varnan

trop tard mais essayez ceci,

 public static String parseDate(String givenDateString) {
    if (givenDateString.equalsIgnoreCase("")) {
        return "";
    }

    long timeInMilliseconds=0;
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    try {

        Date mDate = sdf.parse(givenDateString);
        timeInMilliseconds = mDate.getTime();
        System.out.println("Date in milli :: " + timeInMilliseconds);
    } catch (ParseException e) {
        e.printStackTrace();
    }


    String result = "now";
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

    String todayDate = formatter.format(new Date());
    Calendar calendar = Calendar.getInstance();

    long dayagolong =  timeInMilliseconds;
    calendar.setTimeInMillis(dayagolong);
    String agoformater = formatter.format(calendar.getTime());

    Date CurrentDate = null;
    Date CreateDate = null;

    try {
        CurrentDate = formatter.parse(todayDate);
        CreateDate = formatter.parse(agoformater);

        long different = Math.abs(CurrentDate.getTime() - CreateDate.getTime());

        long secondsInMilli = 1000;
        long minutesInMilli = secondsInMilli * 60;
        long hoursInMilli = minutesInMilli * 60;
        long daysInMilli = hoursInMilli * 24;

        long elapsedDays = different / daysInMilli;
        different = different % daysInMilli;

        long elapsedHours = different / hoursInMilli;
        different = different % hoursInMilli;

        long elapsedMinutes = different / minutesInMilli;
        different = different % minutesInMilli;

        long elapsedSeconds = different / secondsInMilli;

        different = different % secondsInMilli;
        if (elapsedDays == 0) {
            if (elapsedHours == 0) {
                if (elapsedMinutes == 0) {
                    if (elapsedSeconds < 0) {
                        return "0" + " s";
                    } else {
                        if (elapsedDays > 0 && elapsedSeconds < 59) {
                            return "now";
                        }
                    }
                } else {
                    return String.valueOf(elapsedMinutes) + "mins ago";
                }
            } else {
                return String.valueOf(elapsedHours) + "hr ago";
            }

        } else {
            if (elapsedDays <= 29) {
                return String.valueOf(elapsedDays) + "d ago";

            }
            else if (elapsedDays > 29 && elapsedDays <= 58) {
                return "1Mth ago";
            }
            if (elapsedDays > 58 && elapsedDays <= 87) {
                return "2Mth ago";
            }
            if (elapsedDays > 87 && elapsedDays <= 116) {
                return "3Mth ago";
            }
            if (elapsedDays > 116 && elapsedDays <= 145) {
                return "4Mth ago";
            }
            if (elapsedDays > 145 && elapsedDays <= 174) {
                return "5Mth ago";
            }
            if (elapsedDays > 174 && elapsedDays <= 203) {
                return "6Mth ago";
            }
            if (elapsedDays > 203 && elapsedDays <= 232) {
                return "7Mth ago";
            }
            if (elapsedDays > 232 && elapsedDays <= 261) {
                return "8Mth ago";
            }
            if (elapsedDays > 261 && elapsedDays <= 290) {
                return "9Mth ago";
            }
            if (elapsedDays > 290 && elapsedDays <= 319) {
                return "10Mth ago";
            }
            if (elapsedDays > 319 && elapsedDays <= 348) {
                return "11Mth ago";
            }
            if (elapsedDays > 348 && elapsedDays <= 360) {
                return "12Mth ago";
            }

            if (elapsedDays > 360 && elapsedDays <= 720) {
                return "1 year ago";
            }
        }

    } catch (Java.text.ParseException e) {
        e.printStackTrace();
    }
    return result;
}
0
AD 10

Essaye ça

J'étais confronté au même problème ( Exécution non gérée par Java.text.ParseExecption ) lors de la tentative de conversion de l'horodatage au format d'heure précédente, après avoir effectué la R & D, enfin, j'ai trouvé les solutions ... maintenant cette erreur a été résolue 

  • Ajoutez cette dépendance ( compile 'org.ocpsoft.prettytime: prettytime: 4.0.1.Final' ) dans votre bulid.gradle (Module: app) et synchronisez votre projet.
  • Après avoir ajouté cette dépendance, collez cette méthode et appelez-la où vous voulez (Log.e ("TAG", "ConvertTimeStampintoAgo:" + ConvertTimeStampintoAgo (1320917972));)

    public static String ConvertTimeStampintoAgo(Long timeStamp)
    {
    try
    {
        Calendar cal = Calendar.getInstance(Locale.getDefault());
        cal.setTimeInMillis(timeStamp);
        String date = Android.text.format.DateFormat.format("yyyy-MM-dd HH:mm:ss", cal).toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date dateObj = sdf.parse(date);
        PrettyTime p = new PrettyTime();
        return p.format(dateObj);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return "";
    }
    

    Note ça va montrer 

  • il y a un moment (heure actuelle)

  • il y a une minute

  • il y a jour

0
Sunil

Vous pouvez sélectionner le format de type pour lequel les deux méthodes sont testées et fonctionnent correctement.

/ *

* It's return date  before one week timestamp
*  like return
*  1 day ago
*  2 days ago
*  5 days ago
*  21 April 2019
*

* */
public static String getTimeAgoDate(long pastTimeStamp) {

    // for 2 min ago   use  DateUtils.MINUTE_IN_MILLIS
    // for 2 sec ago   use  DateUtils.SECOND_IN_MILLIS
    // for 1 hours ago use  DateUtils.HOUR_IN_MILLIS

    long now = System.currentTimeMillis();

    if (now - pastTimeStamp < 1000) {
        pastTimeStamp = pastTimeStamp + 1000;
    }
    CharSequence ago =
            DateUtils.getRelativeTimeSpanString(pastTimeStamp, now, DateUtils.SECOND_IN_MILLIS);
    return ago.toString();
}


/*
 *
 * It's return date  before one week timestamp
 *
 *  like return
 *
 *  1 day ago
 *  2 days ago
 *  5 days ago
 *  2 weeks ago
 *  2 months ago
 *  2 years ago
 *
 *
 * */

public static String getTimeAgo(long mReferenceTime) {

    long now = System.currentTimeMillis();
    final long diff = now - mReferenceTime;
    if (diff < Android.text.format.DateUtils.WEEK_IN_MILLIS) {
        return (diff <= 1000) ?
                "just now" :
                Android.text.format.DateUtils.getRelativeTimeSpanString(mReferenceTime, now, DateUtils.MINUTE_IN_MILLIS,
                        DateUtils.FORMAT_ABBREV_RELATIVE).toString();
    } else if (diff <= 4 * Android.text.format.DateUtils.WEEK_IN_MILLIS) {
        int week = (int)(diff / (Android.text.format.DateUtils.WEEK_IN_MILLIS));
        return  week>1?week+" weeks ago":week+" week ago";
    } else if (diff < Android.text.format.DateUtils.YEAR_IN_MILLIS) {
        int month = (int)(diff / (4 * Android.text.format.DateUtils.WEEK_IN_MILLIS));
        return  month>1?month+" months ago":month+" month ago";
    } else {
        int year = (int) (diff/DateUtils.YEAR_IN_MILLIS);
        return year>1?year+" years ago":year+" year ago";
    }
}

Merci

0
Yogendra