dont get expected result using method `compareTo()` and `equals()` - android

I need to compare two dates.
which I read one of them from my database that its type is String. so first i convert String to Date in the specific format that i need, then I get the second Date from system again in the format that I want.
my problem is even when they are same i get unexpected result.
my code is:
public class SaharDateComparerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sahar_date_comparer);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String dateString ="18/02/2015";
Date datee = convertStringToDate(dateString);
Log.i("SAHAR","date 1: "+ dateFormat.format(datee).toString());
Date myDate = new Date();
Log.i("SAHAR", "date 2: "+dateFormat.format(myDate).toString());
int testttt= datee.compareTo(myDate);
boolean a = datee.toString().equals(myDate.toString());
Log.i("SAHAR", "date compared: "+String.valueOf(testttt));
Log.i("SAHAR", "date equal: "+String.valueOf(a));
}
public Date convertStringToDate(String strDate) {
// String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date = null;
try {
date = df.parse(strDate);
String newDateString = df.format(date);
System.out.println(newDateString);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
as you can see my two dates are same but i get -1 when i use compareTo() and false when i use equals() method!!!

You should compare your Date objects after clearing the time units missing in the date coming from the database i.e. without hours, minutes, seconds etc. This is what is affecting your results.
String dateString ="18/02/2015";
Date datee = convertStringToDate(dateString);
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
Log.i("SAHAR", "Comparison result: " + datee.equals(c.getTime()));

It's because the two dates have differnt hour,minutes,seconds,... (you don't see when you just do the toString() output)
You can remove them: Compare two dates in Java
Or you make your own Comperator where you just check the day/month/year.

Related

Insert datetime value in android sqlite

I'm having a problem inserting some datetime values in my sqlite database.
I have two datepickers, i can choose a date, but after that, when I insert it into my database, I don't know why but the row for the 2 dates have the current date.. How can I do to insert the date I selected in the datepicker ?
In my database, I declared those columns as DATETIME.
Here's my get-setter class for the dates:
public String getDate_debut() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public void setDate_debut(String date_debut) {
this.date_debut = date_debut;
}
public String getDate_fin() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public void setDate_fin(String date_fin) {
this.date_fin = date_fin;
}
Here's how I get the date of one datepicker. I'm not sure about the way I format my string, and if I need to format or if I can just add as a string.
private DatePickerDialog.OnDateSetListener datepickerdernier
= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
year_x2 = year;
//les DatePicker
month_x2 = month +1;
day_x2 = dayOfMonth;
datefin = (TextView)findViewById(R.id.TVDatePickerDernier);
datefin.setText(year_x2+"-"+month_x2+"-"+day_x2);
}
};
String date2 = datefin.getText().toString();
//im not sure about the following lines
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date_dernier = dateFormat.parse(date2);
And at the end I insert it :
Cours c = new Cours();
c.setBranche_cours(selectedBranche);
c.setDate_fin(date2); //should i set the string ?
dbhelper.Open();
dbhelper.insertCours(c);
How can I insert in my db the date I selected and not the current date?
#UPDATE - **How can I update the date that is inserted ?
I have another activity, and i want to modify the dates I chose before, but I'm not able..
Here's my sqlite method :
public void updateCours(Date olddatedebut, Date newdatedebut, Date olddatedernier, Date newdatedernier)
{
Open();
db.execSQL("UPDATE "+TABLE_COURS+" set "+COLONNE_DATEPREMIER+"=date('"+newdatedebut+"') where "+COLONNE_DATEPREMIER+"=date('"+olddatedebut+"')");
db.execSQL("UPDATE "+TABLE_COURS+" set "+COLONNE_DATEDERNIER+"=date('"+newdatedernier+"') where "+COLONNE_DATEDERNIER+"=('"+olddatedernier+"')");
}
And how I pass that to my method on my activity:
//this is the new date of the 2nd datepicker
String datedernier = convertDateFormat(datenew2, "yyyy-MM-dd", "dd-MMM-yyyy");
//this is the new date of the 1st datepicker
String datepremier = convertDateFormat(datenew1, "yyyy-MM-dd", "dd-MMM-yyyy");
String date_debutold= intent.getExtras().getString("date_debut");
String date_finold=intent.getExtras().getString("date_fin");
//this is the current date recorded in my database from my datepicker
String date_debut1= convertDateFormat(date_debutold, "yyyy-MM-dd", "dd-MMM-yyyy");
//this is the current date recorded in my darabase from my 1st datepicker
String date_fin1= convertDateFormat(date_finold, "yyyy-MM-dd", "dd-MMM-yyyy");
//nouvelledatedebut
Date date_premier= new Date(datepremier);
Date date_dernier = new Date(datedernier);
Date date_premier2 = new Date(date_debut1);
Date date_fin2 = new Date(date_fin1);
dbhelper.Open();
dbhelper.updateCours(selected_brancheold,selectedBranchenew,date_premier2,date_premier,date_fin2,date_dernier,
Thats because you are making some logic on the getter method and setting the new Date(), that will override the date on the date_fin attribute. When you make insertCours probabily this method will try to find all the get methods for the object you are trying to insert. Try change this:
public String getDate_fin() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss");
Date date = new Date();
return dateFormat.format(this.date_fin);
}
to this
public String getDate_fin() {
return this.date_fin;
}
If you still want to add a format to the Date (String), you can still make it on the getter method, but I don't recommend it.
try this
public static String convertDateFormat(String date, String curFormat, String desFormat){
String newFormat = null;
Date frmtDate = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(curFormat);
frmtDate = sdf.parse(date);
SimpleDateFormat formatter = new SimpleDateFormat(desFormat);
newFormat = formatter.format(frmtDate);
} catch (Exception e) {
newFormat = date;
}
return newFormat;
}
sample
String result = convertDateFormat(date2, "yyyy-MM-dd", "dd-MMM-yyyy");
c.setDate_fin(result);
Each value stored in an SQLite database (or manipulated by the
database engine) has one of the following storage classes:
NULL. The value is a NULL value.
INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8
bytes depending on the magnitude of the value.
REAL. The value is a floating point value, stored as an 8-byte IEEE
floating point number.
TEXT. The value is a text string, stored using the database encoding
(UTF-8, UTF-16BE or UTF-16LE).
BLOB. The value is a blob of data, stored exactly as it was input.
There is no DATETIME. SQlite store it as a TEXT. You can't add a day. You have to read it and parse it. And the same goes when you store it. You have to parse it.
Hope it was usefull.

Android DateFormatter print Eastern Daylight Time instead of EDT

So Im trying to print the string "Eastern Daylight Time" instead of EDT . This should be dynamic and not hardcoded. Looking into DateFormatter class did not lead me to an answer that worked.
Here was an example that allows me to format but did not lead me to my specific answer.
I am getting the date back in the following format -
2013-06-08T00:00:00-04:00
Here are somethings that I have tried -
1)
String dateString = changeFormatDateStringWithDefaultTimeZone(paymentConfirmation.getTransactionDate(),
"yyyy-MM-dd'T'HH:mm:ssZ",
"M/d/yyyy hh:mm a zz");
public static String changeFormatDateStringWithDefaultTimeZone(String value, String ip_format, String op_format) {
if (value == null)
return null;
try {
SimpleDateFormat opSDF = new SimpleDateFormat(op_format, Locale.US);
opSDF.setTimeZone(TimeZone.getDefault());
SimpleDateFormat inSDF = new SimpleDateFormat(ip_format, Locale.US);
Date date = inSDF.parse(value);
return(opSDF.format(date));
} catch (Exception e) {
Log.e("Err", "Failed to convert time "+value);
e.printStackTrace();
}
return null;
}
2)
Date today = Calendar.getInstance().getTime();
String todayString = DateUtils.convertDateToStringWithTimeZone(today);
public static String convertDateToStringWithTimeZone(Date date){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = df.format(date);
dateString += " " + TimeZone.getDefault().getDisplayName(false, TimeZone.LONG);
return dateString;
}
These always print timezone as EDT and I want the string Eastern Daylight Time. Can anyone help me out with this?
Okay, based on your last edit of the question, the solution should be like this:
case 1)
The output pattern should be changed to "M/d/yyyy hh:mm a zzzz" (note the count of z-symbols to enforce the full zone name). Depending on the date and the underlying timezone, the formatter SimpleDateFormat will automatically determine if the daylight or the standard name is to be used.
case 2)
Use TimeZone.getDefault().getDisplayName(true, TimeZone.LONG) to enforce the long daylight name. If your default timezone is "America/New_York" then such an expression should print "Eastern Daylight Time". Note that the boolean parameter has been changed to true.

private static final Date myDate =?

I was having difficult to put correct types for:
private static final Date myDate =
I tried to put "mm-dd-yyyy" but it said it cannot be a string.
I tried 'mm-dd-yyyy' but it said too many characters in character literal.
I dont know what is other types I should put. Help please.
If you want to have a Date with a specific time you can use a Calendar object.
If you want to have todays Date you can just use:
private static final Date myDate = new Date();
Specific date:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2015);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date myDate = cal.getTime();
That would be 01.01.2015
Try with this:
SimpleDateFormat f = new SimpleDateFormat("mm-dd-yyyy");
Date date = f.parse(yourString);
I expect it will works for you!
EDIT: It gives to you an error because you are trying set to your variable myDate a String, and it's a type of Date.
Try something like:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
...as you can see here:
http://www.mkyong.com/java/how-to-convert-string-to-date-java/

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 date values

I am using two functions to compare date values where I will be checking to see if start date is greater than/comes after the end date.
The 1st function is used to take in string value and use that string value to initialize the Calendar:
private int getFromCalendar(String strDate,int field)
{
int result = -1;
try
{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");// this is your date format "12/24/2013" = "MM/dd/yyy"
java.util.Date date = formatter.parse(strDate);//convert to date
Calendar cal = Calendar.getInstance();// get calendar instance
cal.setTime(date);//set the calendar date to your date
result = cal.get(field); // get the required field
return result;//return the result.
}
catch (ParseException e)
{
e.printStackTrace();
}
return result;
}
The 2nd function is used to compare the startDate and endDate (they are both buttons):
public void compareDates(String startDate, String endDate){
Calendar startCheckDate = Calendar.getInstance();
int startmm = getFromCalendar(monitoringDate.getText().toString(), Calendar.MONTH);
int startyy = getFromCalendar(monitoringDate.getText().toString(), Calendar.YEAR);
int startdd = getFromCalendar(monitoringDate.getText().toString(), Calendar.DAY_OF_MONTH);
startCheckDate.set(startyy, startmm, startdd);
Calendar endCheckDate = Calendar.getInstance();
int endmm = getFromCalendar(monitoringEndDate.getText().toString(), Calendar.MONTH);
int endyy = getFromCalendar(monitoringEndDate.getText().toString(), Calendar.YEAR);
int enddd = getFromCalendar(monitoringEndDate.getText().toString(), Calendar.DAY_OF_MONTH);
endCheckDate.set(endyy, endmm, enddd);
if(endCheckDate.after(startCheckDate)){
Toast.makeText(getSherlockActivity(), "End date cannot be smaller than start date", Toast.LENGTH_SHORT).show();
}
}
For some reason the compareDates function does not work at all. Help please
You can easily compare date by changing it to milliseconds since 1900
Date date = new Date();
long dateLong = date.getTime();
Now its easy to compare with any other date
So for your case after doing this get back in date DataType
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");// this is your date format "12/24/2013" = "MM/dd/yyy"
java.util.Date date = formatter.parse(strDate);
do something like
long date1long = date1.getTime();
long date2long = date2.getTime();
if(date2long > date1long)
{
// Do whatever you want
}
This is the easiest way to compare two dates
You are way to verbose. Since you only wanted to know if a given date is after another, or not. Here you go:
public class DateTest {
private static SimpleDateFormat formatter = new SimpleDateFormat(
"MM/dd/yyyy");
public static void main(String[] args) throws ParseException {
Calendar start = createFromString("01/30/2013");
Calendar end = createFromString("06/30/2013");
System.out.println("START: " + start.getTime());
System.out.println("END : " + end.getTime());
System.out.println("IS B4: " + isBefore(start, end));
}
public static Calendar createFromString(String date) throws ParseException {
Calendar c = Calendar.getInstance();
c.setTime(formatter.parse(date));
return c;
}
public static boolean isBefore(Calendar start, Calendar end) {
return start.before(end);
}
}
OUTPUT
START: Wed Jan 30 00:00:00 CET 2013
END : Sun Jun 30 00:00:00 CEST 2013
IS B4 : true
I usesd getTime() in the println() method since, the toString() method (that gets implicitly called) on java.util.Date is more human readable than the one in Calendar.
There is also an after() in Calendar and a compareTo().
in the compareDates() use
if(endCheckDate.compareTo(startCheckDate)<0)
instead of
if(endCheckDate.after(startCheckDate))
for more reference go here

Categories

Resources