在我的应用程序中,我正在获取内容的发布日期并以MMM,dd
格式显示它。
它运行良好,但现在我想根据发布日期显示日期格式。
- 如果发布的日期是今天,我想在 24' 小时内显示日期格式(如
19:45
) - 如果发布的日期在 7 天内,我想显示工作日和时间 (
Sunday, 14:30
) - 否则需要显示
MM/dd/yyyy HH:mm:ss
.
为此,我尝试了以下代码:
public static String formateDate( String inputDate )
{
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" );
String lDate = null;
Date date = new Date();
SimpleDateFormat dateFormater =null;
try
{
date = dateFormat.parse( inputDate );
Log.d("debug", "Published Date" + date);
int comparision=diff(date);
Log.d("debug", "Date Comparision" + comparision);
if(comparision==0)
{
dateFormater = new SimpleDateFormat( "kk:mm");
}
else if(comparision>0 && comparision<=7)
{
dateFormater = new SimpleDateFormat( "EEEE kk:mm");
}
else if(comparision > 7)
{
dateFormater = new SimpleDateFormat( "MMM.dd.yyyy kk:mm" );
}
//dateFormater = new SimpleDateFormat( "MMM,dd" );
lDate = dateFormater.format( date );
}
catch( Exception e )
{
e.printStackTrace();
}
return lDate;
}
在这里,我正在计算日子之间的差异
public static int diff( Date date1)
{
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
Date todayDate=new Date();
c1.setTime( date1 );
c2.setTime( todayDate );
int diffDay = 0;
if( c1.before( c2 ) )
{
diffDay = countDiffDay( c1,
c2 );
}
else
{
diffDay = countDiffDay( c2,
c1 );
}
return diffDay;
}
通过这种方式,我能够以某种方式得到我所期望的。但我认为有一个可行的方法,而不是这个。谁能指出我这一点?
long currtime= System.currentTimeMillis();
Calendar calander = Calendar.getInstance();
calander .setTimeInMillis(currtime);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a");
//above line of SDF will give you output in 24 hour format
String dateforrow = dateFormat.format(calander.getTime());
SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
//above line of SDF will give you output in 12 hour format
String dateforrow2 = dateFormat2.format(calander.getTime());