it-swarm.com.de

Wie konvertiere ich die Uhrzeit in "Android"

Mein Server Es zurück zeit: 

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

Ich will 

1: In String konvertieren.

2: Ich möchte "time ago" anzeigen, wenn es vom Server geladen wird.

Bitte. Hilf mir!

15
anh thang Bui

Ich sehe hauptsächlich drei Wege:

a) integrierte Optionen mit SimpleDateFormat und 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) externe Bibliothek ocpsoft/PrettyTime (basierend auf Java.util.Date)

Hier müssen Sie auch SimpleDateFormat verwenden, um das time- Ergebnis als Interpretation von "2016-01-24T16: 00: 00.000Z" zu erzeugen.

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

c) Nutzung meiner Bibliothek Time4A (Schwergewicht, aber mit bester i18n-Unterstützung)

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 - Dateiformat erstellen:

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

2 - Date-Objekt erstellen

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

3 - Verwenden Sie Android DateUtils, um eine Nice Display-Zeichenfolge zu erstellen:

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

Es ist sehr einfach. Ich sage es dir mit meinem 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

In Android können Sie DateUtils.getRelativeTimeSpanString (long timeInMillis) verwenden, indem Sie auf https://developer.Android.com/reference/Android/text/format/DateUtils.html Bezug nehmen Variationen dieser Methode für die Genauigkeit.

5
Marlon López

mit @Excelso_Widi-Code konnte ich überwinden,

Ich habe seinen Code geändert und auch ins Englische übersetzt.

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;

}

}

und ich habe es so benutzt

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

Viel Spaß beim Kodieren und danke @Excelso_Widi du der Mann zwinker

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";
    }
}

rufen Sie einfach getTimeAgo (timeInDate) auf.

Es arbeitet für mich.

4
Kiran

Schritt 1. Konvertieren Sie Ihre Zeitzeichenfolge in Millisekundenformat mit dem langen Typ

Schritt 2. Verwenden Sie den folgenden Code

 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"; } }

// oben Code von Google!

3
GiapLee

Sie können Millisekunden in der Getlongtoago-Methode übergeben und erhalten eine perfekt formatierte Zeichenfolge

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

Was Sie zu konvertieren versuchen, ist ein ISO 8601-kompatibles Format. Der einfachste Weg, dies zu konvertieren, ist die Verwendung der Joda-Time-Bibliothek für Android.

Wenn Sie dies Ihrem Projekt hinzugefügt haben, können Sie diesen Code verwenden, um das genaue Datum zu extrahieren!

    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);

Siehe this , um das Datum in Ihrer bevorzugten Wahl zu formatieren Hoffe, es hilft!

1
OBX

Kotlin-Version 

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

zu spät, aber probieren Sie es aus,

 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

Versuche dies

Ich war vor demselben Problem ( Unhandled exception Java.text.ParseExecption ) beim Versuch, Zeitstempel in das Format time time zu konvertieren. Nachdem ich Forschungs- und Entwicklungsarbeiten durchgeführt hatte, bekam ich schließlich die Lösungen ... nun wurde dieser Fehler behoben 

  • Fügen Sie diese ( compile 'org.ocpsoft.prettytime: prettytime: 4.0.1.Final' ) - Abhängigkeit in Ihrem bulid.gradle (Modul: app) hinzu und synchronisieren Sie Ihr Projekt
  • Fügen Sie nach dem Hinzufügen dieser Abhängigkeit diese Methode ein und rufen Sie sie an der gewünschten Stelle auf (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 "";
    }
    

    Hinweis es wird angezeigt 

  • moment vor (aktuelle Uhrzeit)

  • vor einer Minute

  • vor einem Tag

0
Sunil

Sie können auswählen, welches Schriftformat beide Methoden testen sollen und funktionieren.

/ *

* 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";
    }
}

Vielen Dank

0
Yogendra