Displaying different date formats in the application based on the date comparision

89 views Asked by At

In my application I am getting the published date of a content and showing it in MMM,dd format.

It is working pretty well, but now I want to show the date format based on the published date.

  1. If the published date is today, I want to show the date in 24' hour format (like 19:45)
  2. If the published date is with in 7 days, I want to show the weekday and Time (Sunday, 14:30)
  3. Otherwise need to show MM/dd/yyyy HH:mm:ss.

For this I tried this code:

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

Here I am counting the difference between the days

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

In this way I am able to get somehow what I am expecting. But I think there is a feasible approach rather than this. Can any one point me out for this?

1

There are 1 answers

0
koutuk On
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());