Second EDIT:
Looks like my issue might be where the date is set from the date picker dialog:
// the callback received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear + 1;
mDay = dayOfMonth;
updateDisplay();
}
}
I am +1 to the month, but never taking that off again when i compare for the database...
EDIT:
Okay I did double checked this (finally got to it). Sure enough the
Date test1 = new Date(cobj.getTime().getTime()); //from the Calendar passed in
So the date retrieved from the database is the right date. The one that comes back from my dialog even though it displays correctly using:
String val = cobjstrong text.get(Calendar.MONTH) + "/" +
cobj.get(Calendar.DAY_OF_MONTH) + "/"+ cobj.get(Calendar.YEAR);
...is actually a month ahead when I look at the object as cobj.getTime().getTime(); (a long for the dates I use). Is there some other method or conversion I am missing?
Should I not be using the .getTime on the Calendar Object just to get a long from that (with a call to getTime again on the Date object?). Sometimes it seems to me that my best bet is to store longs in milliseconds to the database and then just retrieve them and do the Date conversions there?
PRE-EDIT question:
SO I have this Date field in a database, that I can store a date to and read a date from, when I read em... I have to add a +1 to the .getMonth() because date returns that as a number 0-11, instead of 1-12. After dealing with this issue and a few others (like .getMinutes returning an int, so if the time is 5:00 only 5:0 is displayed?)but I finally got the date displaying just great, but I found out when I try to query the database on a date things are off I am guessing by one month. So that means a month of
9/8/2011
(dd/mm/YYYY) format, will not query right when using the following ORMLite query:(Notice the .qe, GreaterThanEqual in ormlite).
public void updateDatePickerButtonUI(Calendar cobj, int widget) {
String val = cobj.get(Calendar.MONTH) + "/"+ cobj.get(Calendar.DAY_OF_MONTH)
+ "/"+ cobj.get(Calendar.YEAR);
btnChooseDateReview.setText(val);
//the following just won't query correctly, its a month off
try {
//sessionDate
QueryBuilder<SessionsData, Integer> sb =
mDB.getSessionsDao().queryBuilder();
sb.where().ge(SessionsData.SESSIONSDATE_ID_NAME, cobj.getTime());
List<SessionsData> sessions = mDB.getSessionsDao().query(sb.prepare());
for (int i = 0; i < sessions.size(); i++) {
try {
mDB.getClientsDao().refresh(sessions.get(i).getClient());
mDB.getPackagesDao().refresh(sessions.get(i).getPackage());
} catch (SQLException e) {
...
}
}
theSessions = new CustomSessionReviewAdapter(mContext,
R.layout.session_review_row, sessions);
theSessions.notifyDataSetChanged();
theList.setAdapter(theSessions);
} catch (SQLException e) {
...
}
}
So I must be handling dates wrong, maybe adding to the month for display purposes is not right? or something... maybe in my query with the Calendar object, I can make that month part 0-11 or something...not sure what avenue to take here.
I'm a little confused #CodeJoy. I don't see any references to +1 in your code. I assume that you are doing a +1 while you are building the val for your button text?
ORMLite stores the Date field as a string via the Sqlite driver (i.e. something like 2011-08-10 18:33:30.316) and I am wondering if the conversion to/from a Calendar object generates a Date that does not match the database exactly. Maybe the milliseconds have been truncated? Are you creating a Calendar from the button date string?
Most likely your problem has nothing to do with the +/- 1 issue around the month. The getTime() method should do that conversion appropriately.
I would debug your app and see what the cobj.getTime() returns for a date and then do a mDB.getSessionsDao().queryForAll() and take a look at how the Date is being returned from the database driver.
Related
I want to store date and time that user picks through date picker and time picker on Android. By reading various thread I came to conclusion to store date and time in INTEGER format. So I'm converting them to long values using following function but when I'm converting them back to Date it is giving me wrong Date.
private DatePickerDialog.OnDateSetListener startDatePickerListener = new DatePickerDialog.OnDateSetListener(){
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String dateText = getTimeString(year,monthOfYear,dayOfMonth);
//Converting Date to long so that can be stored in DB
long date = Utility.getDateLong(year,monthOfYear,dayOfMonth);
taskModel.setStartDate(date);
startDateView.setText(dateText);
}
};
public static long getDateLong(int year, int month, int day){
Calendar cal = new GregorianCalendar(year, month, day);
long timeStamp = (cal.getTimeInMillis()+cal.getTimeZone().getOffset(cal.getTimeInMillis()))/1000;
return timeStamp;
}
To convert long value back to Date I'm using the below function :
public static String getDateFromLongValue(long d){
Date date = new Date(d);
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate = dateFormat.format(date);
return formattedDate;
}
But this is giving me the different date then the entered value. Is there any other way to do this. I basically need to compare dates and to find the time elapsed between two dates?
I suggest a duplicate because while "best way" is theoretically debatable, SQLite offers date functions based on the fact that SQLite doesn't have a time and date type, but does offer date functions based ISO-formatted TEXT timestamp.
One item that is definitely not a matter of opinion though is where you want to do the bulk of operations. You have two choices:
Query for a large amount of data then filter that in your app
Query for a subset of that data
You might will run into timing and memory issues if you don't pre-filter your dataset via the query (i.e. using date and time functions off an ISO-formatted text timestamp) and opt to transform epochs in Java.
I store my values in database by converting the date value in milliseconds,so to get the latest date on top by using order by desc query. The order is coming as required but if i enter date 02/01/2016 and 01/30/2016 both are storing same milliseconds value.
String date = "02/01/2016";
String month = date.substring(0, 2);
String day = date.substring(3, 5);
String year = date.substring(6, 10);
Calendar c1 = Calendar.getInstance();
c1.set(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
long left = c1.getTimeInMillis();
After debugging i got the following milliseconds values
02/01/2016----61414914600000
and 01/30/2016----61414914600000
Anybody knows why this happening?
Using SimpleDateFormat value I am getting different milliseconds value:
Date date;
String dtStart = "02/01/2016";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
date = format.parse(dtStart);
long timeMills=date.getTime();
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
I ran your initial code and it functions almost as expected. A few points:
You mention millisecond 61414914600000. That's not correct because it's 1900 years into the future:
http://currentmillis.com/?61414914600000
I'm pretty sure you got that number from a Date object, not from a Calendar: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(int, int, int)
As Mat said the month is zero-based for Calendar and the line where you call the setter should subtract 1:
c1.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
You answered your own question with another snippet of code but Date is deprecated, Calendar should be used instead. Your original code in the initial post was essentially correct (except the zero-based month). You should make sure that you know where your output is coming from and / or that you don't forget to build the code before running it.
I want to let the user choose a Date from a DatePicker and store it into database, and then convert it to dd/mm/yyyy format.
dp =(DatePicker)findViewById(R.id.DateActivity);
setDate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
requestDate.setText("Day" + dp.getDayOfMonth() + " Month " + (dp.getMonth() + 1)+ " Year " + dp.getYear());
}
});
The output is Day 9 Month 2 Year 2014.
The output months is less by one for every month I choose so I add 1 to the month. Why this is the case?
But the main problem is how do I convert it to 09022014 and store it in the database? If the db has the format dd/mm/yyyy does it means it will not accept my output?
java.util.Calendar treats the months as a zero-based list, so the DatePicker follows this convention as well (see the documentation for DatePicker.init). It's confusing, but that's just the way Java does it (for now, at least). Adding 1 like you're doing will work just fine.
As for converting the date, you can use the SimpleDateFormat class to format the date however you like. For what you said, the format pattern string would be "ddMMyyyy". See the sample code below:
// Build Calendar object from DatePicker fields.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, myDatePicker.getMonth());
cal.set(Calendar.DAY_OF_MONTH, myDatePicker.getDayOfMonth());
cal.set(Calendar.YEAR, myDatePicker.getYear());
// Convert date to desired format.
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
String dateString = sdf.format(cal.getTime());
int dateInt = Integer.parseInt(dateString); // if you want it as an int instead
You may want to consider storing the date as 20140209 ("yyyyMMdd", year-month-day) instead for sorting purposes, as that will naturally allow it to be sorted chronologically.
For your second problem (putting it into the database) you can simply create a string like this:
String todb = dp.getDayOfMonth() + "/" + (dp.getMonth() + 1)+ "/" + dp.getYear();
Which will return a string like 09/21/2014.
Now, as for your first problem (the month being off by one), I believe this stems from a CalendarView.OnDateChangeListener. It says:
month The month that was set [0-11].
I would bet that this was also implemented on DatePicker's (or you're using the CalendarView with the DatePicker), so January is 0 and December is 11. So your way of changing the month by 1 is a perfectly fine way to do it.
I have seen many examples of working with dates in Android using Calendar and GregorianCalendar classes.
Recently I came across the following in Android Developers Time documentation:
The Time class is a faster replacement for the java.util.Calendar and java.util.GregorianCalendar classes. An instance of the Time class represents a moment in time, specified with second precision.
This prompted me to replace all the Calendar functions with the faster Time class functions.
Here is my code for reading the date stored in the SQLite database:
// extract milliseconds (long) value from SQLite database
Long timeLong = note.getLong(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_DATE));
Time currentTime.set(timeLong);
Here is the partial code for preparing the integer values for populating the date picker and displaying the formatted date string in the mPickDate button:
mDay = currentTime.monthDay; // Day of the month (0-31)
mMonth = currentTime.month; // Month (0-11)
mYear = currentTime.year; // Year
mPickDate.setText(currentTime.format("%A, %d %b %Y")); // using strftime equivalent to dateFormat = new SimpleDateFormat("E, dd MMM yyyy");
Note the format %A used to get the long string for the day of the week.
This part of the formatting code works perfectly well and displays the correct string with the formatted date, including the correct day of the week.
Clicking on the mPickDate button invokes the DatePicker widget, which allows for changing and setting the new date.
The following code shows the handling of the newly selected date from the DatePicker:
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// new method using Time class
currentTime.set(dayOfMonth, monthOfYear, year);
mPickDate.setText(currentTime.format("%A, %d %b %Y"));
// old method using GregorianCalendar class
//mCalendar = new GregorianCalendar(year, monthOfYear, dayOfMonth);
//mPickDate.setText(dateFormat.format(mCalendar.getTime()));
}
};
The mPickDate button gets the correct date string displayed, as selected in the Date Picker, except for the day of the week (%A), which is always shown as Sunday. Why ?
Note that mPickDate.SetText code is identical to the one used earlier to format the button date string, extracted from the SQLite database field.
I had to modify the above code, by adding an extra line of code to set the date value in the currentTime Time object once again:
currentTime.set(dayOfMonth, monthOfYear, year);
currentTime.set(currentTime.toMillis(true));
mPickDate.setText(currentTime.format("%A, %d %b %Y"));
My question is: why it was necessary to use the currentTime.set procedure twice in the above DatePickerDialog.OnDateSetListener code, in order to get the day of the week string to display correctly ?
Would this possibly be an issue with Android Timecode itself (using SDK version 16) ?
In my application i have 2 field, 1 is date and another is recc(is an integer) in database table.
Now i will explain my requirement:
Consider suppose user enters today's date(26-07-2012) and recc as 10.It means that starting from today's date to that +10 date.I got that 10th date from today's date.But what i want is 10th day from today's date means it will surely go to next month also (26-07-2012----5-08-2012),but i have to know the count of date which falls in this particular month,(i.e)between 26-07-2012----5-08-2012 how many days it will fall within this month.I think i have explained my problem clearly,if not i am ready to give more explanation.Thanks in advance.
Date value:
EditText date=(EditText)findViewById(R.id.startdateexp);
String startdate=date.getText().toString();
you can do this by following way:
1. Get date from Database.
Now get day of month from the date by following method:
DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = iso8601Format.parse(dateTime);
} catch (ParseException e) {
Log.e(TAG, "Parsing ISO8601 datetime failed", e);
}
Calendar cal=Calendar.getInstance();
cal.setTime(date);
int currentDay= cal.get(Calendar.DAY_OF_MONTH);
calculate Last day of month by:
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
If you're using the Date class you can offset it by the number of days converted to milliseconds to create a new Date:
Date datePlusRecc = new Date(oldDate.getTime() + recc*86400000); // 86400000 = 24*60*60*1000
Note that this is useable only when recc is relatively small (< about 20), because otherwise the multiplication will overflow.
Just use the java.util.Date class combined with your date in milliseconds.
In a for loop add one day to the one version in milliseconds and convert it back to Date. Get the Month out of the Date Object and compare it with the current month. As soon as the month is a new one you have your total count of days in the current month.
Date currentDate = new Date(currentMillis);
long countingMillis = currentMillis;
int daysInSameMonth = 0;
while(true){
daysInSameMonth++; // if the actual date schould not count move this line at the button of the while
countingMillis += 1000*60*60*24;
Date dt = new Date(countingMillis);
if(currentDate.getMonth() != dt.getMonth())
break;
}