0

SQL から取得した日付/時刻の値を分割し、メッセージを受信して​​からの分数/時間数を表示する次のコードを Android アプリに実装しました。

//Splits the date and time string retrieved from SQL into two separate strings, 
//and stores them into an array
String[] dt_array = m1.getTime().split(" ");
//String date = dt_array[0]; 
String time = dt_array[1]; 


//Splits the time into two strings, one for hours and one for minutes, and stores them
//into an array
String[] timeSplit = time.split(":");
String hourString = timeSplit[0]; 
String minuteString = timeSplit[1];

//converts the new separate time strings to integer variables
int msgHour = Integer.parseInt(hourString);
int msgMinute =Integer.parseInt(minuteString);

Calendar currentTime = Calendar.getInstance();

//retrieves current hour and minute from device and stores in separate ints 
int currentHour = currentTime.get(Calendar.HOUR);
int currentMinute = currentTime.get(Calendar.MINUTE);

int hoursSince; 
int minutesSince;
String timeDisplay = null;


if (currentHour != 1)
{
    //tells app to display minutes if message was received under an hour ago
    if(currentHour - msgHour < 1)
    {

        minutesSince = currentMinute - msgMinute;
        //if only a minute has passed, text should read "1 minute ago", otherwise use plural "minutes"
        if (minutesSince == 1)
            timeDisplay = minutesSince + " minute ago";
        else
            timeDisplay = minutesSince + " minutes ago";
    }
    else if (currentHour - msgHour >= 1)
    {
        hoursSince = currentHour - msgHour;
        timeDisplay = hoursSince + " hours ago";
    }

} 
else
{
    //for messages that were received at a 12th hour, if the hour is currently 1, correctly displays 1 hour ago
    if(msgHour == 12 && currentHour == 1)
    {
        hoursSince = 1;
        timeDisplay = hoursSince + " hours ago";
    }

}

私が欲しいのは、時間カウントが 24 を超えた場合に受信してからの日数を表示する機能を追加することです。これは簡単なはずですが、Android でそれを行う方法が正確にはわかりません。

4

1 に答える 1

1

メッセージが投稿されてからの経過時間を判断する方法は複雑すぎて、分や時間が繰り越されると問題が発生しやすくなります。このようなものははるかに簡単です:

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm"); //change format as needed
Date messageDate = formatter.parse(date);
long since = System.currentTimeMillis() - messageDate.getTime();
long seconds = since/1000;
long minutes = seconds/60;
long hours = minutes/60;
long days = hours/24;

そこから、必要なメッセージを作成することは簡単です。

于 2013-08-07T19:46:00.240 に答える