how to delete call Log of last 24 hours android - java

public void delete() {
String strUriCalls = "content://call_log/calls";
Uri UriCalls = Uri.parse(strUriCalls);
Cursor cc = getContext().getContentResolver().query(UriCalls, null, null, null, null);
int number = cc.getColumnIndex(CallLog.Calls.NUMBER);
int date = cc.getColumnIndex(CallLog.Calls.DATE);
if (cc.getCount() <= 0)
{
Toast.makeText(getContext(), "Call log empty", Toast.LENGTH_SHORT).show();
}
while (cc.moveToNext()) {
String callNumber = cc.getString(number);
String callDate = cc.getString(date);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
systemDate = Calendar.getInstance().getTime();
String myDate1 = sdf.format(systemDate);
//txtCurrentTime.setText(myDate);
cDate = sdf.format(Long.parseLong(callDate));
Date1 = sdf.parse(myDate1);
Date2 = sdf.parse(cDate);
//to get time diff between current date and call date
millse = Date1.getTime() - Date2.getTime();
mills = Math.abs(millse);
// to change the return value into specific time format
long hh = (mills / (1000 * 60 * 60));
Mins = (int) (mills / (1000 * 60)) % 60;
long Secs = (int) (mills / 1000) % 60;
long timeDifDays = mills / (24 * 60 * 60 * 1000);
if (timeDifDays >= 24) {
int i = getContext().getContentResolver().delete(UriCalls, callNumber, null);
if (i >= 1)
{
Toast.makeText(getContext(), "Number deleted", Toast.LENGTH_SHORT).show();
} else
{
Toast.makeText(getContext(), "No such number in call logs", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}
}
}
It deletes all the records of a particular number if one record satisfies the condition, I want to delete the satisfying record only.

public void delete() {
String strUriCalls = "content://call_log/calls";
Uri UriCalls = Uri.parse(strUriCalls);
Cursor cc = getContext().getContentResolver().query(UriCalls, null, null, null, null);
int number = cc.getColumnIndex(CallLog.Calls._ID);
int date = cc.getColumnIndex(CallLog.Calls.DATE);
if (cc.getCount() <= 0)
{
Toast.makeText(getContext(), "Call log empty", Toast.LENGTH_SHORT).show();
}
while (cc.moveToNext()) {
String callNumber = cc.getString(number);
String callDate = cc.getString(date);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
systemDate = Calendar.getInstance().getTime();
String myDate1 = sdf.format(systemDate);
//txtCurrentTime.setText(myDate);
cDate = sdf.format(Long.parseLong(callDate));
Date1 = sdf.parse(myDate1);
Date2 = sdf.parse(cDate);
//to get time diff between current date and call date
millse = Date1.getTime() - Date2.getTime();
mills = Math.abs(millse);
// to change the return value into specific time format
long hh = (mills / (1000 * 60 * 60));
Mins = (int) (mills / (1000 * 60)) % 60;
long Secs = (int) (mills / 1000) % 60;
long timeDifDays = mills / (24 * 60 * 60 * 1000);
if (timeDifDays >= 24) {
int i = getContext().getContentResolver().delete(UriCalls, BaseColumns._ID+"=?", new String[]{callNumber});
if (i >= 1)
{
Toast.makeText(getContext(), "Number deleted", Toast.LENGTH_SHORT).show();
} else
{
Toast.makeText(getContext(), "No such number in call logs", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}
}
}

Related

Get a timer with less than 60 seconds?

I`m currently trying to obtain a CountDownTimer based on the time in milliseconds of a Calendar object. The startTimer function works, so does the timerSort function. The thing is that when the timer gets initialized with the timeLeft value, it never start from a value lower than 60 seconds. This eventually causes delays bigger than 10 seconds. any suggestions?
Thank you.
Code:
private void startTimer(String x){
counter = new CountDownTimer(timeLeft,1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeft = millisUntilFinished;
updateCountdownText();
}
#Override
public void onFinish() {
timerRunning = false;
int comp = Integer.parseInt(x);
Toast.makeText(getApplicationContext(), "Alarm received!", Toast.LENGTH_LONG).show();
cal[comp].add(Calendar.MINUTE,rec[comp]);
//Update txt file
int month = cal[comp].get(Calendar.MONTH)+1;
int day = cal[comp].get(Calendar.DAY_OF_MONTH);
String data = cal[comp].get(Calendar.HOUR_OF_DAY) + ","
+cal[comp].get(Calendar.MINUTE) + ","
+day+ "," + month + ","
+cal[comp].get(Calendar.YEAR) + "," + rec[comp] + ",";
try {
FileOutputStream stream = new FileOutputStream(file[comp], false);
try {
stream.write(data.getBytes());
}catch (Exception e){
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//end update
timerSort();
BluetoothGattCharacteristic C = btper.getCharacteristic(UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"),UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"));
//If device is disconnected => it will crash
btper.writeCharacteristic(C , x.getBytes(StandardCharsets.UTF_8), WriteType.WITH_RESPONSE);
speak(String.valueOf(comp+1));
}
}.start();
}
private void updateCountdownText() {
if(counterView.getVisibility() != View.VISIBLE)
counterView.setVisibility(View.VISIBLE);
int minutes = (int)timeLeft / 1000 / 60;
int seconds = (int)timeLeft /1000 % 60;
String timeLeftFormatted = String.format(Locale.getDefault(),"Time left until next pill: %02d:%02d",minutes,seconds);
if(timeLeftFormatted.contains("00:00"))
counterView.setVisibility(View.INVISIBLE);
counterView.setText(timeLeftFormatted);
}
private void resetTimer(){}
private void timerSort(){
Context context = getApplicationContext();
int i,j;
j = 0;
int fileindex = 0;
int hour, day, month, minute, year;
calendar = Calendar.getInstance();
timeLeft = 0;
for (i = 0; i<20; i++){
fileindex = i+1;
file[i] = new File(context.getExternalFilesDir(null).getAbsolutePath(),"pills"+fileindex+".txt");
cal[i] = (Calendar) calendar.clone();
//Read text from pills file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file[i]));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
String str = text.toString();
List<String> elephantList = Arrays.asList(str.split(","));
hour = Integer.parseInt(elephantList.get(0));
minute = Integer.parseInt(elephantList.get(1));
day = Integer.parseInt(elephantList.get(2));
month = Integer.parseInt(elephantList.get(3));
year = Integer.parseInt(elephantList.get(4));
rec[i] = Integer.parseInt(elephantList.get(5));
cal[i].set(Calendar.HOUR_OF_DAY, hour);
cal[i].set(Calendar.MINUTE, minute);
cal[i].set(Calendar.DAY_OF_MONTH, day);
cal[i].set(Calendar.MONTH-1, month);
cal[i].set(Calendar.YEAR,year);
}
// sorting:
int letsgo = 0;
Calendar tudor = Calendar.getInstance();
tudor.set(Calendar.YEAR,calendar.getMaximum(Calendar.YEAR));
for (i = 0; i<20; i++){
if(tudor.after(cal[i]) && cal[i].after(calendar)){
tudor = cal[i];
letsgo = i;
}
}
Toast.makeText(getApplicationContext(), String.valueOf(letsgo), Toast.LENGTH_LONG).show();
TextView nextPillView = (TextView) findViewById(R.id.nextPillView);
if (!cal[letsgo].after(calendar)) {
nextPillView.setText("No Pills Scheduled");
} else {
// timeLeft = cal[letsgo].getTimeInMillis() - calendar.getTimeInMillis() - Calendar.MILLISECOND;
int secleft = cal[letsgo].get(Calendar.SECOND)-calendar.get(Calendar.SECOND);
int minleft = cal[letsgo].get(Calendar.MINUTE)-calendar.get(Calendar.MINUTE);
timeLeft = secleft*1000 + minleft*60*1000 ;
//timeLeft = cal[letsgo].getTimeInMillis() - calendar.getTimeInMillis();
String theTime = String.format(Locale.getDefault(), "%02d:%02d", cal[letsgo].get(Calendar.HOUR_OF_DAY), cal[letsgo].get(Calendar.MINUTE));
month = cal[letsgo].get(Calendar.MONTH)+1;
nextPillView.setText(cal[letsgo].get(Calendar.HOUR_OF_DAY)+":"+cal[letsgo].get(Calendar.MINUTE)+ " | | Day: " + cal[letsgo].get(Calendar.DAY_OF_MONTH) + " | | Month: " + String.valueOf(month) + " | | Year: " + cal[letsgo].get(Calendar.YEAR));
startTimer(String.valueOf(letsgo));
}
}
private void speak(String x){
float pitch = 1;
float speed = 1;
mTTS.setPitch(pitch);
mTTS.setSpeechRate(speed);
mTTS.speak("It is time to administer the compartment with the lit LED",
TextToSpeech.QUEUE_ADD,null);
}

How to fix error with CountDownTimer in android app

I'm trying to make a countdown in days, hours, minutes, seconds from a starting date and I'm getting the days wrong for some reason I cannot find.
String givenDateString = "2019-05-15T09:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
new CountDownTimer(timeInMilliseconds, 1000) {
#Override
public void onTick(long millisUntilFinished) {
long day = TimeUnit.MILLISECONDS.toDays(millisUntilFinished);
millisUntilFinished -= TimeUnit.DAYS.toMillis(day);
long hour = TimeUnit.MILLISECONDS.toHours(millisUntilFinished);
millisUntilFinished -= TimeUnit.HOURS.toMillis(hour);
long minute = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished);
millisUntilFinished -= TimeUnit.MINUTES.toMillis(minute);
long second = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished);
prueba.setText("Days: "+day+" Hours: "+hour+" Minutes: "+minute+" Seconds: "+second);
}
#Override
public void onFinish() {
// What ever you want !
}
}.start();
And I'm getting this result:
New error android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
TextView prueba;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prueba = findViewById(R.id.prueba);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date currentDate = null;
Date destinationDate = null;
try {
currentDate = Calendar.getInstance().getTime();
destinationDate = sdf.parse("2019-05-15T09:00:00");
} catch (ParseException e) {
e.printStackTrace();
}
calculateDifference(currentDate, destinationDate);
}
}, 0, 1000);//Update text every second
}
public void calculateDifference(Date startDate, Date endDate) {
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long days = different / daysInMilli;
different = different % daysInMilli;
long hours = different / hoursInMilli;
different = different % hoursInMilli;
long minutes = different / minutesInMilli;
different = different % minutesInMilli;
long seconds = different / secondsInMilli;
Log.e("calculation", "Days: " + days + " Hours: " + hours + " Minutes: " + minutes + " Seconds: " + seconds);
prueba.setText("Days: " + days + " Hours: " + hours + " Minutes: " + minutes + " Seconds: " + seconds);
}
Hello there here is how you can achieve this
Here is the method which calculate the difference between two date.
public void calculateDifference(Date startDate, Date endDate) {
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long days = different / daysInMilli;
different = different % daysInMilli;
long hours = different / hoursInMilli;
different = different % hoursInMilli;
long minutes = different / minutesInMilli;
different = different % minutesInMilli;
long seconds = different / secondsInMilli;
Log.e("calculation", "Days: " + days + " Hours: " + hours + " Minutes: " + minutes + " Seconds: " + seconds);
}
You can settext of you text view instead of log
And this is how you can call the timer with date
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date currentDate = null;
Date destinationDate = null;
try {
currentDate = Calendar.getInstance().getTime();
destinationDate = sdf.parse("2019-05-15T09:00:00");
} catch (ParseException e) {
e.printStackTrace();
}
calculateDifference(currentDate, destinationDate);
}
}, 0, 1000);//Update text every second
}

How to find difference between to dates [duplicate]

This question already has answers here:
getting the difference between date in days in java [duplicate]
(3 answers)
Calculating the difference between two Java date instances
(45 answers)
Closed 6 years ago.
I have two dates with string format "16-Feb-2017", "26-Feb-2017"
and I used
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
but I am unable to get exact result like "10".
Hope this will help you.pass your dates in myDate and time_ago.
int totalMin;
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH);
Date systemDate = Calendar.getInstance().getTime();
String myDate = sdf.format(systemDate);
Date Date1 = null;
try {
Date1 = sdf.parse(myDate);
} catch (ParseException e) {
e.printStackTrace();
}
Date Date2 = null;
try {
Date2 = sdf.parse(time_ago);
} catch (ParseException e) {
e.printStackTrace();
}
assert Date2 != null;
assert Date1 != null;
long millse = Date1.getTime() - Date2.getTime();
long mills = Math.abs(millse);
Hours = (int) (mills / (1000 * 60 * 60));
Mins = (int) (mills / (1000 * 60)) % 60;
Secs = (int) (mills / 1000) % 60;
long diffDays = millse / (24 * 60 * 60 * 1000);
if (Secs >= 60) {
Mins = Mins + 1;
Secs = Secs - 60;
} else if (Mins >= 60) {
Hours = Hours + 1;
Mins = Mins - 60;
}
totalMin = (int) ((Mins) + (Secs / 60));
String t_time;
if (diffDays > 0) {
if (diffDays == 1) {
t_time = diffDays + " day";
} else {
t_time = diffDays + " days";
}
} else if (Hours > 0) {
if (Hours == 1) {
t_time = Hours + " hour";
} else {
t_time = Hours + " hours";
}
} else if (Mins > 0) {
if (Mins == 1) {
t_time = totalMin + " minute";
} else {
t_time = totalMin + " minutes";
}
} else {
if (Secs == 1) {
t_time = Secs + " second";
} else {
t_time = Secs + " seconds";
}
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
java.time.LocalDate d1 = java.time.LocalDate.parse("16-Feb-2017", formatter);
java.time.LocalDate d2 = java.time.LocalDate.parse("26-Feb-2017", formatter);
Period until = d1.until(d2);
System.out.println("Dif: " + until.getDays());
Please use below code to init SimpleDateFormat.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
As I already said in a comment, use Java 8 java.time classes if you can. kamehl23’s answer shows you how. It’s a both elegant and robust solution, also across changes to and from summer time (DST).
EDIT: Stuck with an older Java version, they say you can use either ThreeTenABP or Joda time, I haven’t tried any of them. ThreeTenABP, I read, is an Android adaption of a backport of java.time to Java 6 and 7, so I would be tempted to give that a shot.
You can of course get through with Java 1.1 Calendar. The solution that also works across summer time change is:
String formattedDate1 = "16-Feb-2017";
String formattedDate2 = "26-Feb-2017";
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy", YOUR_LOCALE);
Date d1 = df.parse(formattedDate1);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(d1);
Date d2 = df.parse(formattedDate2);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(d2);
int daysBetween = 0;
while (cal1.before(cal2)) {
daysBetween++;
cal1.add(Calendar.DATE, 1);
}
System.out.println(daysBetween);
This prints 10. It’s neither very elegant nor very efficient, but it works robustly as long as the ‘from’ date is before (or the same as) the ‘to’ date (which can easily be checked).

How to find the duration of difference between two dates

I have two dates, eg. 1989-3-21, 2016-3-21 and I want to find the duration of difference between those dates. For this I am trying the following code but I am unable to get the duration of difference in dates.
public String getTimeDiff(Date dateOne, Date dateTwo) {
String diff = "";
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
diff = String.format("%d hour(s) %d min(s)", TimeUnit.MILLISECONDS.toHours(timeDiff),
TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
return diff;
}
Initialize your dates like so before calling public String getTimeDiff(Date dateOne, Date dateTwo):
Date dateOne=null,dateTwo=null;
try {
dateOne = new SimpleDateFormat( "yyyy-MM-dd" ).parse("2016-3-21");
dateTwo = new SimpleDateFormat( "yyyy-MM-dd" ).parse("1989-3-21");
}
catch (ParseException ex) {
}
System.out.println( getTimeDiff(dateOne,dateTwo));
public String getTimeDiff(Date dateOne, Date dateTwo) {
String diff = "";
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
diff = String.format("%d date(s) ", TimeUnit.MILLISECONDS.toDays(timeDiff));
return diff;
}
Since your Dates aren't in their default format you will have to use a SimpleDateFormat to explicitly declare the format of your Dates.
From here
long diff = dt2.getTime() - dt1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));
Try Using This
try {
/// String CurrentDate= "10/6/2016";
/// String PrviousDate= "10/7/2015";
Date date1 = null;
Date date2 = null;
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
date1 = df.parse(CurrentDate);
date2 = df.parse(PrviousDate);
long diff = Math.abs(date1.getTime() - date2.getTime());
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println(diffDays);
} catch (Exception e) {
System.out.println("exception " + e);
}
Take the difference and and call the method;
long diff = dt2.getTime() - dt1.getTime();
public static String toHumanReadableTime(long diff) {
Long hour = TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);
diff= diff% (1000 * 60 * 60);
Long minutes = TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS);
diff= diff% (1000 * 60);
Long seconds = TimeUnit.SECONDS.convert(diff, TimeUnit.MILLISECONDS);
diff= diff% 1000;
Long milisec = diff;
StringBuilder buffer = new StringBuilder();
if (hour != null && hour > 0) {
buffer.append(hour).append(" Hour ");
}
if (minutes != null && minutes > 0) {
buffer.append(minutes).append(" Minute ");
}
buffer.append(seconds).append(" Second ");
buffer.append(milisec).append(" Millisecond ");
return buffer.toString();
}

How to get "Time Difference" in "since/ago"? Is this possible without use of any library?

I want to change the format of, Currently Date(YYYY-MM-DD) and Time (SS:MM:HH) to 'n' Months ago,'n' Days ago , 'n' Hours "ago" format.
CURRENT FORMAT:
REQUIRED FORMAT:
I am using Bean and Adapter class to get Current Date. Code is given Below;
Adapter Class:
public class MessageAdapter extends BaseAdapter {
private Activity activity;
private List<MessageBean> messageBeanList;
public ImageLoader imageLoader;
private Context context;
public MessageAdapter (Activity activity,List<MessageBean> messageBeanList)
{
super();
this.activity = activity;
// this.context = context;
this.messageBeanList = messageBeanList;
this.context=context;
}
#Override
public int getCount() {
return messageBeanList.size();
}
#Override
public Object getItem(int position) {
return messageBeanList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ItemHolder itemHolder = new ItemHolder();
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) activity.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(
R.layout.message_item, null);
imageLoader=new ImageLoader(activity.getApplicationContext());
itemHolder.timestampp = (TextView) convertView
.findViewById(R.id.timestamp);
convertView.setTag(itemHolder);
} else {
itemHolder = (ItemHolder) convertView.getTag();
}
class ItemHolder
{
public TextView timestampp;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
// Your code to nofify
}
}
BEAN CLASS:
import com.google.gson.annotations.SerializedName;
public class MessageBean {
#SerializedName("date_created")
private String dateCreated = "";
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
Gone through almost every related question in SOF, but didn't get what I want as I am using bean and adapter class. Is this possible to convert Date and Time format if using JSON parsing?
I hope this will work for you..
Just add code in your adapter
/***************get current date time function*************/
String curDateTime = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
String curDateTime = df.format(c.getTime());
}catch(Exception e){}
/***************get current date time function*************/
// add simple_date_format for uniqueness
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = simpleDateFormat.parse(messageBean.getDateCreated()); // like 2016-03-09 07:08:27
Date date2 = simpleDateFormat.parse(curDateTime); // 2016-03-09 07:08:27
differentDateTime = printDifference(date1, date2);
} catch (Exception e) {
e.printStackTrace();
}
itemHolder.timestampp.setText(differentDateTime);
/************function of print different for showing date into ago format***************/
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public String printDifference(Date startDate, Date endDate){
String allDaysMonsSeconds="";
//milliseconds
long different = endDate.getTime() - startDate.getTime();
Log.d("TAG","startDate : " + startDate);
Log.d("TAG","endDate : "+ endDate);
Log.d("TAG","different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long yearInMilli = daysInMilli * 365;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
long elapsedYears = different / yearInMilli;
Log.d("TAG","%d days, %d hours, %d minutes, %d seconds %n, %d years:"+elapsedDays+","+elapsedHours+","+elapsedMinutes+","+elapsedSeconds+","+elapsedYears);
// code for showing before days...
if(elapsedDays<=0){
if (elapsedHours<=0)
{
if (elapsedMinutes<=0)
{
allDaysMonsSeconds = elapsedSeconds+" second ago";
}
else
{
allDaysMonsSeconds = elapsedMinutes+" minute ago";
}
}
else
{
allDaysMonsSeconds = elapsedHours+" hour ago";
}
}
else{
allDaysMonsSeconds = elapsedDays+" day ago";
}
return allDaysMonsSeconds;
}
/************function of print different for showing date into ago format***************/
try this,
initialize your textview first.
TextView t = new TextView();
Call below method as,
getTimeDifference(date, t);
private void getTimeDifference(String pDate, TextView time) {
int diffInDays = 0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar c = Calendar.getInstance();
String formattedDate = format.format(c.getTime());
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(formattedDate);
d2 = format.parse(pDate);
long diff = d1.getTime() - d2.getTime();
diffInDays = (int) (diff / (1000 * 60 * 60 * 24));
if (diffInDays > 0) {
if (diffInDays == 1) {
time.setText(diffInDays + " day ago");
} else {
time.setText(diffInDays + " days ago");
}
} else {
int diffHours = (int) (diff / (60 * 60 * 1000));
if (diffHours > 0) {
if (diffHours == 1) {
time.setText(diffHours + " hr ago");
} else {
time.setText(diffHours + " hrs ago");
}
} else {
int diffMinutes = (int) ((diff / (60 * 1000) % 60));
if (diffMinutes == 1) {
time.setText(diffMinutes + " min ago");
} else {
time.setText(diffMinutes + " mins ago");
}
}
}
} catch (ParseException e) {
// System.out.println("Err: " + e);
e.printStackTrace();
}
}
Use the following code and just concatenate ago as a string in the time:
startTime = "2016-03-09 16:23:30";
StringTokenizer tk = new StringTokenizer(startTime);
String date = tk.nextToken();
String time = tk.nextToken();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
SimpleDateFormat sdfs = new SimpleDateFormat("hh:mm a");
Date dt;
try {
dt = sdf.parse(time);
System.out.println("Time Display: " + sdfs.format(dt)+" ago"); // <-- I got result here
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String curDateTime = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
String curDateTime = df.format(c.getTime());
}catch(Exception e){}
/***************get current date time function*************/
// add simple_date_format for uniqueness
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = simpleDateFormat.parse(messageBean.getDateCreated()); // like 2016-03-09 07:08:27
Date date2 = simpleDateFormat.parse(curDateTime); // 2016-03-09 07:08:27
differentDateTime = printDifference(date1, date2);
} catch (Exception e) {
e.printStackTrace();
}
itemHolder.timestampp.setText(differentDateTime);
/************function of print different for showing date into ago format***************/
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public String printDifference(Date startDate, Date endDate){
String allDaysMonsSeconds="";
//milliseconds
long different = endDate.getTime() - startDate.getTime();
Log.d("TAG","startDate : " + startDate);
Log.d("TAG","endDate : "+ endDate);
Log.d("TAG","different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long yearInMilli = daysInMilli * 365;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
long elapsedYears = different / yearInMilli;
Log.d("TAG","%d days, %d hours, %d minutes, %d seconds %n, %d years:"+elapsedDays+","+elapsedHours+","+elapsedMinutes+","+elapsedSeconds+","+elapsedYears);
// code for showing before days...
if(elapsedDays<=0){
if (elapsedHours<=0)
{
if (elapsedMinutes<=0)
{
allDaysMonsSeconds = elapsedSeconds+" second ago";
}
else
{
allDaysMonsSeconds = elapsedMinutes+" minute ago";
}
}
else
{
allDaysMonsSeconds = elapsedHours+" hour ago";
}
}
else{
allDaysMonsSeconds = elapsedDays+" day ago";
}
return allDaysMonsSeconds;
}

Categories

Resources