I have a simple form with a DatePicker component on it. The user can enter their date of birth and then submit the form. Once submitted they are shown a review of what they entered into the form. I have every other component on the form working apart from the DatePicker. I am successfully passing a value from the DatePicker into my Intent but for some reason I am getting a very strange, undesired date...
Does anyone know how I can retrieve the actual values the user put in? Below is a screen of what I am getting in the emulator.
This is the part of my code in my onCreate method where I put the date info into the intent
Date myDate = new Date(date.getDayOfMonth(), date.getMonth(), date.getYear());
i.putExtra("dob", myDate.toString());
And then in the activity to show the results this is the code where I display the information pulled from the intent.
dob.setText("Their date of birth is: " + extras.get("dob"));
As you can see I do successfully get output, it's just not the date that I select on the DatePicker itself. I get no runtime errors at all. It's a formatting thing I think. Not sure though so any feedback is appreciated!
I corrected the issue. Rather then creating a Date object and passing it into my intent I decided to retrieve the values from the DatePicker and storing them in integer variables.
int day = date.getDayOfMonth();
int month = date.getMonth();
int year = date.getYear();
i.putExtra("day", day);
i.putExtra("month", month);
i.putExtra("year", year);
Following this I then retrieved the values from the Intent in the new Activity, formatted them and displayed them in a TextView.
int day = extras.getInt("day");
int month =extras.getInt("month");
int year = extras.getInt("year");
dob.setText("Their date of birth is: " + String.valueOf(day) + "/" + String.valueOf(month + 1) + "/" + String.valueOf(year));
I had to add 1 to the month as for some reason If I chose January it would output 0.
Related
i have the following code:
Log.e(TAG, "startTime = " + startTime);
DateTime dateTimeStart = new DateTime(startTime);
Log.e(TAG, "dateTimeStart = " + dateTimeStart );
.
which when logged out produces the following:
startTime = 2014-10-30T12:00:00+00:00
dateTimeStart = 2014-10-30T13:00:00.000+01:00
.
Why is an extra hour getting added on to the original time?
edit
How can i remove the +1:00, i haven't specified that.
Thanks
DateTime is an object consisting of a date, a time, and a timezone. In your case, you took startTime and converted it into an equivalent DateTime using the default system timezone.
+01:00 means "this timestamp is in some UTC+1 timezone", so 12:00:00.000+00:00 means the same as 13:00:00.000+01:00
So your timestamp was created at 12:00 British time = 13:00 Central European time.
If you want the time in UTC, do
DateTime dateTimeStart = new DateTime(startTime, DateTimeZone.UTC);
Use split method.
String splitDateTime[]=dateTimeStart.split("\\+");
dateTimeStart=splitDateTime[0];
Default DateTime::toString() method returns date in format yyyy-MM-ddTHH:mm:ss.SSSZZ .
+01:00 and +00:00 are the timezone offsets (ZZ in date format).
So if you want to print date without timezone offset, you should use another format. E.g. with method DateTime::toString(String):
String dtFormat = "yyyy-MM-dd'T'HH:mm:ss";
Log.e(TAG, "startTime = " + startTime.toString(dtFormat));
...
Log.e(TAG, "dateTimeStart = " + dateTimeStart.toString(dtFormat ));
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 am currently working on my project for my professional course. I am implementing a digital diary.
I would be having a diary page (a multiline textbox maybe) And a TextView on top to show the current DATE (without time). How do I show a NON-editabale textbox with today's date shown in it.
In order to get the current date and time use the below Links and iin order make it non editable in XML file make editable = false also focusable = false.
LINK1
LINK2
its simple
Date dt = new Date();
int date = dt.getDate();
int month = dt.getMonth()+1;
int year = dt.getYear();
year += 1900;
int day = dt.getDay();
String[] days = { "Sunday", "Monday", "Tuesday","WednesDay", "Thursday", "Friday", "Saterday" };
String curDate = date + "/" + month + "/" + year + " " + days[day];
Use this code :
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
It 'll print :
Feb 5, 2013, 12:35:46PM
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.
I have a program which should display the current time. It displays the right time immediately after I install it to a phone. But after that, whenever I run the application, the time doesn't change at all.
Here's my code:
Calendar cal = new GregorianCalendar();
hour = cal.get(Calendar.HOUR);
minute = cal.get(Calendar.MINUTE);
second = cal.get(Calendar.SECOND);
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH)+1;
day = cal.get(Calendar.DATE);
date = day+"_"+month+"_"+year+"_";
Current_Time = date+ hour + "_" + minute + "_" + second;
Shekhar... I had the same misunderstanding. When you create an instance of calendar, it represents the date at which it was instantiated and that state does not change! So, to get the current "date" you need to create a new instance.
JAL
You can write it as a method. Each call to create a new instance of the Calendar