Date and Date format Calculation Android - android

I have a function with date calculations. It compares the database from and to date which I already retrieved, with the input from and to date which I am passing. While debugging, it showing wrong dates after assignment inside the for loop.(input and database dates) Below I shown the example with a image.
Function code:
/*String[] veh - vehicle name, String[] from - table from date array,
* String[] to - table to date array,String from1 - input from date, String to1 - input to date*/
private List getDateComparison(String[] veh, String[] from, String[] to,String from1, String to1) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM",Locale.ENGLISH);
Date table_from,table_to,input_from,input_to;
long diff=0,diff1=0,diff2=0,diff3=0;
int count=0,county=0;;
for(int i=0;i<veh.length;i++){
table_from=df.parse(from[i]);
table_to=df.parse(to[i]);
input_from=df.parse(from1);
input_to=df.parse(to1);
table_from=df.parse(df.format(table_from));
table_to=df.parse(df.format(table_to));
input_from=df.parse(df.format(input_from));
input_to=df.parse(df.format(input_to));
diff=table_from.getTime()-input_from.getTime();
diff1=table_from.getTime()-input_to.getTime();
diff2=input_from.getTime()-table_to.getTime();
diff3=input_to.getTime()-table_to.getTime();
if((diff > 0 && diff1>0) || (diff2 > 0 && diff3>0)){
count++;
removeAndAddList(veh[i],1);
Log.d("Date", " ok with from");
}
else {
county = 100;
removeAndAddList(veh[i],2);
}
}
return vehic;//= veh[0];
}
Function Screenshot while Debugging:
Edited:
Before I used the date format as,
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
At that time the calculation worked perfectly. Now it was making some issues with the date format. I think my dateformat is doing something wrong inside the for loop. It was showing bigger dates after assigning the dates with dateformat. Where I did wrong?

The format you are using for the SDF is not correct
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM",Locale.ENGLISH);
as M means Month in year and you are using it as minutes.
change to HH:mm
... = new SimpleDateFormat("yyyy-MM-dd HH:mm",Locale.ENGLISH);
off-topic:
instead of using diff=table_from.getTime()-input_from.getTime(); you can make use of after() and before() methods for Date
you can compare dates as following (from your code):
if((diff > 0 && diff1>0) || (diff2 > 0 && diff3>0)){
will be:
if((table_from.after(input_from) && table_from.after(input_to))
|| (input_from.after(table_to) && input_to.after(table_to))){
now you can remove all the getTime() subtraction lines from the code (the 4 lines)

Related

Difficulty getting data from Sqlite database between two days

I was doing an Android app that generates sales report for dates between the current date and seven days in the past. It worked fine, here's the code:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR,-7);
String currentDate = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String sevenDayAgo = sdf.format(calendar.getTime());
Cursor weeklyIncome = db.getResult("select sum(price) as total_income from sales where date between '"+sevenDayAgo+"' and '"+currentDate+"'");
Cursor weeklyCost = db.getResult("select sum(purchase_price * quantity) as total_cost from sales where date between '"+sevenDayAgo+"' and '"+currentDate+"'");
Say for example currentDate = 31-08-2018 and sevenDayAgo = 24-08-2018 this all worked fine but when I change my system date to the next day which is the next month and currentDate becomes 01-09-2018 the query doesn't return anything from the database, it should have returned records between 25-08-2018 and 01-09-2018 which has seven days in between. Somehow the query doesn't work when the 7 days are in two different months. I don't know what's going on and how to fix it.
p.s. The date column in sales table is of type TEXT.
The problem is the format you're using for dates (dd-mm-yyyy) isn't in lexicographic order. The string '25-08-2018' compares greater than '01-09-2018' . x BETWEEN y AND z is equivalent to x >= y AND x <= z. That condition won't be true for dates in that range using your format (Remember, they're just strings. sqlite does not have a date type.
You should be using ISO-8601 formats, like yyyy-mm-dd. These will sort properly ('2018-08-25' < '2018-09-01') and will allow you to use the sqlite3 date and time functions on them.
Suppose user has entered the birth date in 31/08/2018 this format :
Parse it like :
String[] parts = BirthField.getText().toString().trim().split("/");
int CAL_DAY, CAL_MONTH, CAL_YEAR;
if(parts.length == 3)
{
CAL_DAY = Integer.parseInt(parts[0]);
CAL_MONTH = Integer.parseInt(parts[1]);
CAL_YEAR = Integer.parseInt(parts[2]);
}
You can check if user has entered a good date or not with :
if( CAL_DAY > 0 && CAL_DAY < 32 && CAL_MONTH > 0 && CAL_MONTH < 13 && CAL_YEAR > 1900 )
While storing in database table take below care :
Calendar CalendarEvent = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
CalendarEvent.set(Calendar.DATE, CAL_DAY);
CalendarEvent.set(Calendar.MONTH, CAL_MONTH - 1);
CalendarEvent.set(Calendar.HOUR_OF_DAY, Integer.parseInt(ScheduleTime) );
CalendarEvent.set(Calendar.MINUTE, 00);
CalendarEvent.set(Calendar.SECOND, 00);
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.getDefault());
String DayConsidered = format.format(CalendarEvent.getTime());
Please note CAL_MONTH - 1 as system starts months from 0 to 11
While storing store in database in SystemTime like :
SYSTIME = CalendarEvent.getTimeInMillis();
While using it again retrieve it from database and initialise calendar event with it like :
Calendar CalendarEvent = Calendar.getInstance();
CalendarEvent.setTimeInMillis( Long.parseLong(SYSTIME) );
int CAL_DAY = CalendarEvent.get(Calendar.DAY);
CalendarEvent.set(Calendar.DATE, CAL_DAY - 7);
And it will start working for even if days / months / even you change years from any date; it will always show the date which is less than 7 days
Hope it helps and let me know how it works as i am answering it quick...
Edit : 2
Better and most efficient way which i am using in my project and working perfectly is :
Log.d("ADDING A MONTH :", "ADDING 1 MONTH....\n");
CalendarEvent.add(Calendar.MONTH, 1);
Log.d("NEGATING 7 DAYS :", "NEGATING 7 DAYS....\n");
CalendarEvent.add(Calendar.DATE, -7);

How to compare time ranges?

Hi i am trying to compare time ranges,My requirement is when i select time from time-picker dialog it should be under given time ranges for this i wrote below code this is working when i not select 12 or 00 from time picker dialog
start time:06:00
end time:23:00
selected time from time picker dialog:12:23
above timing not suitable for below code can some one help me please
String pattern = "hh:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date1 = sdf.parse(startTime);
Date date2 = sdf.parse(endTime);
Date date3 = sdf.parse(selectedTime);
if (((date3.after(date1) || date3.equals(date1)) && (date3.before(date2) || date3.equals(date2)))) {
}
else {
Toast.makeText(context, "Pickup time should be open and close timings", Toast.LENGTH_SHORT).show();
}
You can use code below .
String pattern = "HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
Date date1 = sdf.parse(startTime);
Date date2 = sdf.parse(endTime);
Date date3 = sdf.parse(selectedTime);
if (date3.compareTo(date1) >= 0 && date3.compareTo(date2) <= 0) {
// Do your stuff
} else {
// Wrong time
}
} catch (Exception e) {
e.printStackTrace();
}
h represents Hour in am/pm (1-12)
H represents Hour in day (0-23)
Your date is in 24 hour formate so you should use H instead of h.
You should use compareTo().
CompareTo method must return negative number if current object is less
than other object, positive number if current object is greater than
other object and zero if both objects are equal to each other.
Code Reference
if (date1.compareTo(date2) < 0)
{
Log.d("RESULT","date1 older than date2");
}
else
{
Log.d("RESULT","date2 older than date1");
}
NOTE
Make sure your TIME format is perfect.

Joda - Get the age from a birthday using a different format

I'm learning how to build Android applications, and I'm trying to get the age from my users, only using the birthday.
I'm already using Joda timer, but I'm getting the data from a Json file, and this Json file outputs the data like this:
1994-11-24 / YYYY-MM-d
I'm getting the json data inside a for loop, in Java.
//Variable
private static final String TAG_BIRTH_DATE = "birth_date";
...
//inside the Loop
String birth_date = c.getString(TAG_BIRTH_DATE);
My question is, how can I format the date, and get the age from the person?
I tried this, so far.
DateTimeFormatter formatter = DateTimeFormat.forPattern("d/MM/yyyy");
LocalDate date = formatter.parseLocalDate(birth_date);
LocalDate birthdate = new LocalDate (date);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
But is not working.
Thank you.
Try below method to calculate age of user and in parameter pass your date that you are getting from JSON
public static int getAge(String dateOfBirth) {
Calendar today = Calendar.getInstance();
Calendar birthDate = Calendar.getInstance();
int age = 0;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateOfBirth);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
birthDate.setTime(convertedDate);
if (birthDate.after(today)) {
throw new IllegalArgumentException("Can't be born in the future");
}
age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
// If birth date is greater than todays date (after 2 days adjustment of
// leap year) then decrement age one year
if ((birthDate.get(Calendar.DAY_OF_YEAR)
- today.get(Calendar.DAY_OF_YEAR) > 3)
|| (birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH))) {
age--;
// If birth date and todays date are of same month and birth day of
// month is greater than todays day of month then decrement age
} else if ((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH))
&& (birthDate.get(Calendar.DAY_OF_MONTH) > today
.get(Calendar.DAY_OF_MONTH))) {
age--;
}
return age;
}
You have just mismatched your pattern and then accepted an answer which uses minutes instead of months (small "m" versus big "M). The Joda-answer would be (pay attention to the different pattern please):
String birth_date = c.getString(TAG_BIRTH_DATE); // example: 1994-11-24
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-d");
LocalDate date = formatter.parseLocalDate(birth_date);
Years age = Years.yearsBetween(date, LocalDate.now());

Comparison of Date and Time

I have to get count of days which are past to the current day.I have list of days in arraylist.I got the list and I dont know how to compare?Can anyone help me?
This is the code I tried,
private void weeklylogeval(){
int i;
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormatter.setLenient(false);
Date today = new Date();
String s = dateFormatter.format(today);
System.out.println("current date & time new:::"+s);
for(i=0;i<datetime.size();i++){
String daytime=datetime.get(i);
if(today.before(daytime))
}
}
Pls some one help me!
Try this code for date difference manipulation.
String fd=from_date;//date get from mysql database as string.
String td=to_date;//Today's date as string.
if(!fd.equalsIgnoreCase("") && !td.equalsIgnoreCase("")){
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat formatter;
Date frmdt=new Date(fd);
formatter = new SimpleDateFormat("dd/MM/yyyy");
String s1 = formatter.format(frmdt);
Date todt=new Date(td);
String s2 = formatter.format(todt);
Date frmdate = sdf.parse(s1);
Date todate = sdf.parse(s2);
if(frmdate.compareTo(todate)<=0) {
//do your stuff
} else {
// do your stuff
}
}
http://developer.android.com/reference/java/util/Calendar.html
This should be allot easier to use for your purpose
Edit:
Methods you can use:
boolean after(Object calendar)
Returns whether the Date represented by this Calendar instance is after the Date represented by the parameter.
boolean before(Object calendar)
Returns whether the Date represented by this Calendar instance is before the Date represented by the parameter.
Maybe you can construct a Date form the String you get from DB, and then use today.before(daytime) to compare them.
Date daytime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(datetime.get(i));

Comparing formatted dates

I create a date and then format is like this:
Example 1:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
String currentDate = sdf.format(new Date());
What I would like to do is check if this date is before another date (also formatted the same way). How would I go about doing this?
Example 2:
Also, how would I check whether one of these is before another:
long setForLong = System.currentTimeMillis() + (totalTime*1000);
String display = (String) DateFormat.format("HH:mm:ss dd/MM/yyyy", setForLong);
EDIT:
I think more detail is needed. I create a date in two different ways for two different uses. The first use just formats the current date into a string so it is readable for the user. In the second case, I am using a date in the future with System.currentTimeMillis and adding on a long. Both result in a string.
Both methods format the date in exactly the same way, and I set the strings into a TextView. Later, I need to compare these dates. I do not have the original data/date/etc, only these strings. Becasue they are formatted in the same way, I though it would be easy to compare them.
I have tried the if(String1.compareTo(String2) >0 ) method, but that does not work if the day is changed.
If you only have two String objects that are dates available to you. You will need to process them in something, either in your own comparator class or in another object. In this case, since these are already formatted into dates, you can just create Date objects and compare using the methods previously posted. Something like this:
String string = "05:30:33 15/02/1985";
Date date1 = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.ENGLISH).parse(string);
String string2 = "15:30:33 01/02/1985";
Date date2 = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.ENGLISH).parse(string2);
if(date1.getTime()>date2.getTime()) {
//date1 greater than date2
}
else if(date1.getTime()<date2.getTime()) {
//date1 less than date2
}
else {
//date1 equal to date2
}
You should use Calendar for convenient comparing dates.
Calendar c1 = Calendar.getInstance();
c1.setTime(Date someDate);
Calendar c2 = Calendar.getInstance();
c2.setTime(Date anotherDate);
if(c1.before(c2)){
// do something
}
And you can format it at any time
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
String currentDate = sdf.format(c1.getTime());

Categories

Resources