How to find difference two dates on android app [duplicate] - android

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculate date/time difference in java
I am a new on Android and I want to make a new app for me. I want to subtruct two dates (dd/mm/yyyy) format by using currentDate. For example I want to find the differences of the days between 01/02/2013 and currentDate. How can I do it?

SimpleDateFormat dfDate = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date d = null;
java.util.Date d1 = null;
Calendar cal = Calendar.getInstance();
try {
d = dfDate.parse("01/02/2012 ");
d1 = dfDate.parse(dfDate.format(cal.getTime()));//Returns 15/10/2012
} catch (java.text.ParseException e) {
e.printStackTrace();
}
int diffInDays = (int) ((d.getTime() - d1.getTime())/ (1000 * 60 * 60 * 24));
System.out.println(diffInDays);
Check Ex1 and Ex2 for more detailed example

You may take a look into DateUtils, that offers some utility methods to compute elapsed time between two dates, but only for representation. Do not use the direct approach to convert between days/milliseconds since it does not take into consideration leap years, leap seconds, summer/winter time changes, etc. Those considerations are handled by Calendar classes.
Update
You can use Joda library to perform relative date and time calculations like the one you need.

Related

best way to get timestamp in long in android? [duplicate]

This question already has answers here:
Which one is recommended: Instant.now().toEpochMilli() or System.currentTimeMillis()
(4 answers)
JSR 310 :: System.currentTimeMillis() vs Instant.toEpochMilli() :: TimeZone
(3 answers)
Closed 3 years ago.
I want to understand this in detail on how to get this in android and which method to follow and please explain bit more to understand in better way ?
As we have some options to get this in android and find out the best.
It will be helpful if somebody explains with code how to get this.
Thanks in advance for your help
Hi I hope this will help you
//Getting the current date
Date date = new Date();
//This method returns the time in millis
long timeMilli = date.getTime();
System.out.println("Time in milliseconds using Date class: " + timeMilli);
//creating Calendar instance
Calendar calendar = Calendar.getInstance();
//Returns current time in millis
long timeMilli2 = calendar.getTimeInMillis();
System.out.println("Time in milliseconds using Calendar: " + timeMilli2);
//Java 8 - toEpochMilli() method of ZonedDateTime
System.out.println("Getting time in milliseconds in Java 8: " +
ZonedDateTime.now().toInstant().toEpochMilli());
And output fo these options will be
Time in milliseconds using Date class: 1508484583259
Time in milliseconds using Calendar: 1508484583267
Getting time in milliseconds in Java 8: 1508484583331
if we convert those long values to the date format then all three will be the same and it will be
Input 1508484583259
Input (formatted) 1,508,484,583,259
Date (Etc/UTC) Friday, October 20, 2017 7:29:43 AM UTC
Date (GMT) Friday, October 20, 2017 7:29:43 AM GMT
Date (short/short format) 10/20/17 7:29 AM
Over here I posted only one option result but all three will be the same or you can also check it by your own on online long to date convertor.
For getting timestamp in millisecond just call:
//kotlin
val tstamp = System.currentTimeMillis()
//java
long tstamp = System.currentTimeMillis();

Android Current Time [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I want to show current time of device in app. following is the code is getting time but problem is if current time is 12:15 but my variable cTime has opposite time that is 00:15. Below is my code for getting time, please help me out
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Calendar c = Calendar.getInstance();
int currentHour = c.get(Calendar.HOUR);
int currentMin = c.get(Calendar.MINUTE);
String currentTime = currentHour+":"+currentMin;
Date cTime = sdf.parse(currentTime);
You should use Calendar.HOUR_OF_DAY instead of Calendar.HOUR to get the hour in 0-24 format.
Try this Code For current time
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm aa");
String datetime = sdf.format(now);
Use this simple method for get device current time in milisecound
System.currentTimeMillis();
Always, always read the documentation for the code you're using.
You are formatting your hours with the H pattern, which describes the 24 hour model:
H | Hour in day | (0-23) | Number | 0
You need to use the small h, which represents the “Hour in am/pm (1-12)”:
SimpleDateFormat format = new SimpleDateFormat("hh:mm");
Date date = new Date();
String dateReadable = format.format(date);
// Use your String elsewhere.
And this is all you need to get started. No need to create ints and Calendars for this. You can also put the a for the period indicator, as Arjun said below.
This is the foundation for this answer, too, but considering the code is slightly different and you are facing difficulties (by looking at your code), I didn't consider it a duplicate.

Calender Date Difference Calculation error in Android

I know there are many formats of example to calculate the two dates difference. I tried in a way from that one. My answer is always correct if I input the dates within a single month. If I go for finding difference more than a month it was not giving correct answer. It was always finding the difference for two dates. How can I find date difference more that 31 days or 2016-01-05 to 2015-12-13.
Date oldDate,newDate;
SimpleDateFormat dateFormat;
//editText1=2015-12-13
//editText2=2016-01-05
oldDate = dateFormat.parse(editText1.getText().toString());
newDate = dateFormat.parse(editText2.getText().toString());
oldDate=dateFormat.parse(dateFormat.format(oldDate));
newDate=dateFormat.parse(dateFormat.format(newDate));
long diff = newDate1.getDate() - oldDate1.getDate();
editText3.setText(""+(diff+1));
Convert the dates to timestamps in milliseconds, subtract one from the other, and divide the result by 86400000 (milliseconds in a day).
long oldTime, newTime;
oldTime = dateFormat.parse(editText1.getText().toString()).getTime();
newTime = dateFormat.parse(editText2.getText().toString()).getTime();
long daysDiff = Math.abs(newTime - oldTime) / DateUtils.DAY_IN_MILLIS;

Time plus minutes

I have a bunch of data containing a time value, e.g. 09:30am, and a duration, either 15,30,45 or 60. What would be the best way of getting the end time from these values? Will it be some use of a Date / Calendar or would just a custom function be quicker to do?
The Joda Time library (http://www.joda.org/joda-time/) is popular, easy to work with, and handles these kinds of calculations in a straight-forward manner.
DateTime start = new DateTime(2013, 10, 15, 9, 30); // create a DateTime representing Oct 15, 2013 at 9:30
Duration dur = Duration.standardMinutes(15); // create a duration of 15 minutes
DateTime calc = start.plus(dur); // add; result is 9:45 on 10/15/2013
The standard java/android way for this is to use a calendar:
final Calendar c = Calendar.getInstance(); // now
c.add(Calendar.DAY_OF_MONTH, 10); // add 10 days
There are other constants if you want to add minutues, years, seconds, ....
Check out this solution: Java string to date conversion
You may need to change the "MMMM d, yyyy" portion to fit your data set.
Here is the Javadoc: http://developer.android.com/reference/java/text/SimpleDateFormat.html
edit: For the second part of your question, there are several questions on here about how to add to a Date/Calendar object.

How to calculate the total number of days passed [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculate date/time difference in java
I am providing the user with the option to select the date using Date Picker. Is there any in-built method using which I can calculate the duration in days wrt to user selected date and todays date.
I don't like answering this because there were millions of questions like this (use search option before posting questions). Use Joda Time. There is a Period class, which will be useful for you.
Get the difference between the two times in milliseconds. Than you can get the Days via Java's Calendar class.
Date today = new Date(); // the date of today
Date target = new Date(); // the date of when the user picks
long todayEpoch = today.getTime(); // or can use = System.currentTimeMillis();
long targetEpoch = target.getTime();
long daysInMs = targetEpoch - todayEpoch; //days in MS's
//the # of days
float days = (daysInMs/1000/60/60/12);

Categories

Resources