web-dev-qa-db-ja.com

androidで時間を「時間前」に変換する方法

私のサーバー。それは時間を返します:

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

が欲しいです

1:文字列に変換します。

2:サーバーからロードするときに「時間前」を表示したい。

お願いします。助けて!

21
anh thang Bui

主に3つの方法があります。

a)SimpleDateFormatおよび 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)外部ライブラリ ocpsoft/PrettyTimeJava.util.Dateに基づく)

ここでは、「[2016-01-24T16:00:00.000Z」の解釈としてSimpleDateFormat- resultを生成するために、timeも使用する必要があります。

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

c)ライブラリを使用する Time4A (重量がありますが、i18n-supportが最適です)

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

1-日付フォーマッターを作成します:

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

2-日付オブジェクトの作成

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

3-Android DateUtilsを使用してNice Display文字列を作成します。

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

とても簡単です。私のコードで説明します。

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();
        }
    }
}
11

Android使用できますDateUtils.getRelativeTimeSpanString(long timeInMillis)https://を参照) developer.Android.com/reference/Android/text/format/DateUtils.html その方法のバリエーションの1つを使用して正確にすることができます。

8
Marlon López

@Excelso_Widiコードを使用して、私は克服することができました、

私は彼のコードを修正し、英語に翻訳しました。

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;

}

}

そして、私はこのようにそれを使用しました

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

ハッピーコーディングと@Excelso_Widiありがとうございますwink

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

getTimeAgo(timeInDate);を呼び出すだけです。

それは私のために働いています。

4
Kiran

手順1.時間型をlong型のミリ秒形式に変換する

ステップ2.以下のコードを使用する

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

// Googleからのコードの上!

3
GiapLee

Getlongtoagoメソッドでミリ秒を渡すことができ、完全なフォーマットされた文字列を返します

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

変換しようとしているのはISO 8601準拠フォーマット。これを変換する最も簡単な方法は、Androidで Joda-Timeライブラリ を使用することです。

それをプロジェクトに追加すると、このコードを使用して正確な日付を抽出できます!

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

また、 this を参照して、好みの選択で日付をフォーマットしてください。

1
OBX

コトリン版

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"
    }
}
1
Kavin Varnan
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;

  }

}
1
Excelso Widi

両方のメソッドをテストして正常に動作させるために、どのタイプのフォーマットを選択することができます。

/ *

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

ありがとう

1
Yogendra

手遅れですが、これを試してください、

 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
Adil

これを試して

私は同じ問題に直面していました(nhandled execption Java.text.ParseExecption)タイムスタンプを時間前の形式に変換しようとしたときに、R&Dを行った後、最終的に解決策を得ました...今、このエラーは解決されました

  • Bulid.gradle(Module:app)にthis(compile 'org.ocpsoft.prettytime:prettytime:4.0.1.Final')依存関係を追加し、プロジェクトを同期します
  • この依存関係を追加したら、このメソッドを貼り付けて好きな場所に呼び出します(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 "";
    }
    

    表示されます

  • 一瞬前(現在の時刻)

  • 分前

  • 日前

0
Sunil