Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Thursday, 29 December 2016

Difference between two date in android



package com.samset.user.sample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TimeUtils;
import android.view.View;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {


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

        String first="12/29/2016 09:29:58 AM"
        String second="12/29/2016 09:29:58 PM"

        String SubscriptionEndTime = first;
        String currentTime = "12/29/2016 04:31:48 PM";

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a", Locale.ENGLISH);

        try {
            Date date = dateFormat.parse(currentTime);
            Date date1 = dateFormat.parse(SubscriptionEndTime);

             Log.d("difference>>>",computeDiff(date,date1).toString());


        } catch (ParseException e) {
            e.printStackTrace();
        }

    }


    public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {
        long diffInMillies = date2.getTime() - date1.getTime();
        List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
        Collections.reverse(units);
        Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
        long milliesRest = diffInMillies;
        for ( TimeUnit unit : units ) {
            long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
            long diffInMilliesForUnit = unit.toMillis(diff);
            milliesRest = milliesRest - diffInMilliesForUnit;
            result.put(unit,diff);
        }
        return result;
    }

}


output:-

Result 1:-  difference>>>:

DAYS=0,
HOURS=-7,
MINUTES=-1,
SECONDS=-50,
MILLISECONDS=0,
MICROSECONDS=0,
NANOSECONDS=0


Result 2:- difference>>>:

DAYS=0,
HOURS=4,
 MINUTES=58,
 SECONDS=10,
 MILLISECONDS=0,
 MICROSECONDS=0,
 NANOSECONDS=0