gpt4 book ai didi

安卓:比较日期

转载 作者:行者123 更新时间:2023-11-29 05:22:52 24 4
gpt4 key购买 nike

我正在尝试将从 MySQL 检索到的日期与当前日期/时间进行比较。

我想要的效果是这样的:

Date is Recent (Less than an hour)               | 0
Date is An Hour Ago (1-2 Hours before now) | 1
Date is Several Hours Ago (2-8 Hours before now) | 2
Date is Yesterday (a day ago) | 3
Date is Recent (More than a day ago) | 4

说明:该方法会返回一个0-4(含)之间的数字作为选择。

我目前有一堆乱七八糟的代码,但也许有人可以建议更好的方法?

比较日期方法:

private int compareDate(Date date1)
{
long daysAgo = getDaysAgo(date1);

if(daysAgo == 0)
{
//Check the hours

int choice = getMinAgo(date1);

//Code for "Minutes Ago"
if(choice == 0)
{
return 0;
}

//Code for "An Hour Ago"
else if(choice == 1)
{
return 1;
}

//Code for "Several Hours Ago"
else if(choice == 2)
{
return 2;
}

else return -1;

}

else if (daysAgo == 1)
{
//"Code" for "Yesterday" is 3
return 3;
}

else
{
//"Code" for "Several days ago" is 4
return 4;
}
}

getDaysAgo 方法

private long getDaysAgo(Date date)
{
long days = (new Date().getTime() - date.getTime()) / DAYS_IN_MILLISEC;

return days;
}

getMinAgo 方法

private int getMinAgo(Date date)
{
long hourAgo = 60;
long twoHourAgo = hourAgo*2;
long eightHourAgo = hourAgo*8;

Date dateHourAgo = new Date(date.getTime() - hourAgo*60*1000);
Date dateTwoHourAgo = new Date(date.getTime() - twoHourAgo*60*1000);
Date dateEightHourAgo = new Date(date.getTime() - eightHourAgo*60*1000);

//Between 0-1 Hours Ago
if(date.before(dateHourAgo))
{
return 0;
}

//Between 1-2 Hours Ago
else if(date.after(dateHourAgo) && date.before(dateTwoHourAgo))
{
return 1;
}

else if(date.after(dateTwoHourAgo) && date.before(dateEightHourAgo))
{
return 2;
}

return -1;
}

最佳答案

下面的代码是一个示例,您可以如何实现该方法(我将其命名为 getChoice)。我已经测试过了并且工作正常。如果有什么不清楚的地方,请不要犹豫并询问。

import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Date testedDate = new Date(114, 4, 10, 22, 0, 0);
TextView tv = (TextView)findViewById(R.id.textView1);

int i = getChoice(testedDate);
String mOutput = String.valueOf(i);

tv.setText("The output is: " + mOutput);

}

private int getChoice(Date d) {
long mTime = new Date().getTime() - d.getTime();

if(mTime <= 3600000) return 0; // less than an hour
if(mTime <= 7200000) return 1; // 1-2 hours before now
if(mTime <= 28800000) return 2; // 2-8 hours before now
if(mTime <= 86400000) return 3; // a day ago
return 4; // more than a day ago
}

}

关于安卓:比较日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23596448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com