Time manipulation for android - android

Hi every one i want to devolepe an Alarm App i get the sunrise and sunset time from webservice now i need to manipulate these timing my date store in string when i calculate difference it give correct result when i add two time values it cause problem like
i try it like below to get the manipulated time that i applied manipulation but
it give wrong result
SimpleDateFormat sdf = new SimpleDateFormat("kk:mm:ss");
Date Date1 = sdf.parse(sunrsetat);
Date Date2 = sdf.parse("00:12:00");
long millse = Date1.getTime() + Date2.getTime();
long mills = Math.abs(millse);
int Hours = (int) (mills/(60*60*1000));<------ here it give hour 09 and it must be 19
int Mins = (int) (mills/(1000*60)) % 60;
long Secs = (int) (mills / 1000) % 60;
String time = String.format("%02d:%02d:%02d", Hours, Mins, Secs);
hanfiaiftaritime.setText(time);

Error occurs because Date.getTime() returns millis since Jan 1, 1970, so your mills field has value (assuming date1 < date2) of 2*date1 + difference-in-millis-date2-date1. (http://developer.android.com/reference/java/util/Date.html#getTime())
Solution: use Calendar class.
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
calendar.add(Calendar.SECOND, (int) date2.getTime() / 1000);
long millse = calendar.getTimeInMillis();
In this case computing hours/mins/seconds becomes redundant cause you can use http://developer.android.com/reference/java/util/Calendar.html#get(int) like this:
int hours = calendar.get(Calendar.HOUR_OF_DAY);

Related

Difference between two Times in Minutes are coming as negative

I have a method which takes two String parameters. the two strings are Time values in 24 hour format. The Times are picked using a TimePicker from UI.
The goal of the method is to get the duration between the StartTime and EndTime in Minutes.
public static String getTimeDuration(String StartTime24, String EndTime24)
{
String duration = "";
try
{
SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm");
Date startTime = parseFormat.parse(StartTime24);
Date endTime = parseFormat.parse(EndTime24);
long mills = endTime.getTime() - startTime.getTime();
long minutes = mills/(1000 * 60);
duration = "(" + minutes + " Minutes)";
}
catch(ParseException ex)
{
// exception handling here
}
return duration;
}
The method works fine if both the times are within a Single Date. For example:
StartTime = 22:15
EndTime = 23:51
Output = (96 Minutes)
But my problem is, the method returns negative if the end time is after 12'o clock at night. For example,
StartTime = 23:51
EndTime = 0:55
Output = (-1376 Minutes)
What I want: (64 Minutes)
How can get the duration correct ?
As there is no date used, you have to check first if your endTime is less than your startTime. If yes, then your endTime is on the next day and you have to add 1 day/86 400 000 milliseconds. Then you will have your desired result.
Just add this condition:
if(endTime.getTime() < startTime.getTime()){
long mills = ((endTime.getTime() + 86400000) - startTime.getTime()); 1 day = 86 400 000 mill
}
Hope this helps
You're only parsing the minutes and hours. There's no day on there. So that puts both times on the same day (the first day of the epoch, Jan 1 1970 to be exact). So the answer is correct. If you want it to treat the end time as the next day if its earlier than the start time, then add 1 day to the result (1440 minutes) if the result is less than 0.

How to calculate elapsed time and date in android

I want my app to show the time elapsed from the point an entry was stored in the database to the point it is fetched from the database.
I am currently doing something like this which gives me time elapsed in seconds:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss aa");
Date systemDate = Calendar.getInstance().getTime();
String myDate = sdf.format(systemDate);
Date Date1 = sdf.parse(myDate);
Date Date2 = sdf.parse(savedDate);
int dateDiff = getTimeRemaining();
long millse = Date1.getTime() - Date2.getTime();
long mills = Math.abs(millse);
long Mins = mills/(1000*60);
String diff = +dateDiff+ "days " + Mins+ " mins";
cal[1] = "" +Mins;
t3.setText(diff);
But I also want it to include the no of days since the data was stored. As of now, it resets when the day is over. I want it to give me the total minutes after N days. How should I do it? Thanks in advance.
You firstly need to determine the number of seconds from database-stored-time until now.
long ageOfDatabaseEntry = (System.currentTimeMillis() - databaseEnteredTimeMillis)
You then need to determine how many days you want, then modulo the age by that number to get the remaining number of milliseconds.
long getRemainingMinutes(long age, int days) {
// Use the modulus operator to get the remainder of the age and days
long remainder = age % (days * 86400000);
if(remainder == age) {
throw new InvalidArgumentException("The number of days required exceeds the age of the database entry. Handle this properly.");
}
// Turn the remainder in milliseconds into minutes and return it
return remainder / 60000;
}

how to get correct date diffrence

i want to compare a date with the current date and do something if the difference is 2 months or 6 or a year .. but i have a problem how to get the correct difference for example if the current month is 02 2015 and the other month is 10 2014 i will get 8 in difference but the actual difference is 4 .. how to do it ?
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat d = new SimpleDateFormat("dd");
SimpleDateFormat m = new SimpleDateFormat("MM");
SimpleDateFormat ye = new SimpleDateFormat("yyyy");
String day = d.format(c.getTime());
String month = m.format(c.getTime());
String year = ye.format(c.getTime());
int d1=Integer.parseInt(day);
int m1=Integer.parseInt(month);
int d2=25;
int m2=02;
int diff=d1-d2;
String s=String.valueOf(diff);
You are calculating your difference between two int, so it can't work.
You should calculate it between two dates or two long (in secondes or milliseconds)
long oneDay, today, delay;
oneDay = 1000*3600*24; //number of milliseconds in a day
today = Calendar.getInstance().getTimeInMillis();
delay = (TheDateYouWantToCompare - today)/oneDay;
if (delay >= 60*oneDay) { //more than 2 months
//your code
}else{
//your code
}
If TheDateYouWantToCompare and today are dates, it's almost the same :
delay = (TheDateYouWantToCompare.getTime() - today.getTime())/oneDay;
Edit :
Here it is how to get time in milliseconds.
String DateString = "31-12-2015";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date myDate = sdf.parse(DateString);
long timeInMilliseconds = myDate.getTime();
You could just use the difference in milliseconds between the 2 dates. Pre-compute the differences you need/want as constants and compare to the delta you have, for example:
static final long DAY = 1000 * 60 * 60 * 25;
static final long MONTH = DAY * 30;
...
int diff = d1 - d2;
if(diff > MONTH) {
//more than a month difference
}
If you need something more complex you should perhaps use a library such as Joda Time which will give a more comprehensive set of features to work with time.

Subtract two datepickers in android [duplicate]

This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Closed 8 years ago.
Is there any way to subtract two dates from picker.
Example:
I will select a date from picker1 and date from picker2.
Then, picker2 - picker1 to get the number of days between these two dates.
20/10/2014
(-) 06/10/2014
--------------
14 days
DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
try {
Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");
Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55");
obj.printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
}
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate){
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
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;
System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays,
elapsedHours, elapsedMinutes, elapsedSeconds);
}
output is this
startDate : Thu Oct 10 11:30:10 SGT 2013
endDate : Sun Oct 13 20:35:55 SGT 2013
different : 291945000
3 days, 9 hours, 5 minutes, 45 seconds
Answer from this link Android difference between Two Dates
Since not much information is provided, I assume you are using DatePicker
The basic flow is like that:
by calling getDayOfMonth(), getMonth() and getYear() from DataPicker to obtain day, month and year respectively.
after obtaining those information, I think you should be able to calculate the day difference between them.
Just for your reference, the following is a topic about day difference, hope this help.
Difference in days between two dates in Java?
short and simple
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date1 = null;
java.util.Date date2 = null;
try {
date1 = simpleDateFormat.parse("20/10/2014");
date2 = simpleDateFormat.parse("06/10/2014");
} catch (java.text.ParseException e) {
e.printStackTrace();
}
int diffInDays = (int) ((date1.getTime() - date2.getTime())/ (1000 * 60 * 60 * 24));
EDIT :
Hello Uday
it is Very Simple you have two EditText so first Set your date into et and et1 and now
et.getText().toString(); //Do same for et1 also
this mothod will helps you for getting date and now apply to my code

Calculating elapsed time between two dates, gives different results in different devices

Im trying to get the time elapsed from a specific date (in millis)
In some devices I get the correct result
however, in other devices I get wrong result
here's the code that i use:
public static void timeElapsedFromDate(long workingDate)
{
long diff = System.currentTimeMillis() - workingDate;
long diffSeconds = diff / 1000;
long diffMinutes = diffSeconds / 60;
long diffHours = diffMinutes / 60;
long diffDays = diffHours / 24;
long diffWeeks = diffDays / 7;
long diffMonth = diffDays / 30;
}
Isn't it the way to measure time?
thanks!
First of all, diffMonth formula asks to be improved: from Feb 1st to Mar 1st it is usually 28 days, but one month. From Sep 1st to Sep 31st it is 30 days, but less than 1 month.
More subtle question regarding diffDays: isn't it 1 day between 10 PM and 10 AM next morning?
Finally, how different devices can give different results: System.currenTTimeMillis() returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. Even if the clock on all devices is correct, they may have different Time Zone settings.
public int getElapsedTimeInDays(Date start,Date end){
int days=(int)(start.getTime()-end.getTime())/(1000*60*60*24);
return days;
}
public int getElapsedTimeInHours(Date start,Date end){
int hours=(int)(start.getTime()-end.getTime())/(1000*60*60);
return hours;
}
public int getElapsedTimeInMinutes(Date start,Date end){
int minutes=(int)(start.getTime()-end.getTime())/(1000*60);
return minutes;
}
public int getElapsedTimeInSecunds(Date start,Date end){
int scunds=(int)(start.getTime()-end.getTime())/(1000);
return secunds;
}
//Then you can use the codes like this:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd, hh:mm");
Date start = df.parse("2012-01-12, 09:35");
Date end = new Date();//this will be the curent date;
int day = getElapsedTimeInDays(start,end);

Categories

Resources