I have a serious problem here, I am building an app that will work on Arabic devices, and I need to send dates to the server, I am using Android DatePickerDialog to get the date, but the date always sent with Arabic characters, and when i try to display it again it gives me Unparsable date exception
I have tried the following solutions but no results
mDateTime = Calendar.getInstance(Locale.US).getTime();
mDateFormater.setTimeZone(TimeZone.getTimeZone("GMT"));
but non of them worked for me
any help please.
My date picker dialog code is like following
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
private TextView mUserView;
private Date mAffectedDate;
private SimpleDateFormat mDateFormater;
private Date mInitialDate;
public TextView getUserView() {
return mUserView;
}
public void setUserView(TextView userView) {
this.mUserView = userView;
}
public Date getAffectedDate() {
return mAffectedDate;
}
public void setAffectedDate(Date mAffectedDate) {
this.mAffectedDate = mAffectedDate;
}
public SimpleDateFormat getDateFormater() {
return mDateFormater;
}
public void setDateFormater(SimpleDateFormat mDateFormater) {
this.mDateFormater = mDateFormater;
}
public Date getInitialDate() {
return mInitialDate;
}
public void setInitialDate(Date mInitialDate) {
this.mInitialDate = mInitialDate;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance(Locale.US);
c.setTime(mInitialDate);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Date date = new Date();
date.setYear(year - 1900);
date.setMonth(month);
date.setDate(day);
mAffectedDate.setYear(year - 1900);
mAffectedDate.setMonth(month);
mAffectedDate.setDate(day);
mUserView.setText(mDateFormater.format(date));
}
}
You can use:
Calendar.set(int year, int month, int day, int hourOfDay, int minute, int second)
Sets the year, month, day of the month, hour of day, minute, and second fields. Other fields are not
changed; call clear first if this is not desired. The month value is 0-based, so it may be clearer to use a constant like JANUARY.
Like this:
Calendar cal = Calendar.getInstance(Locale.US);
public void onDateSet(DatePicker view, int year, int month, int day) {
cal.set(year, month, day, 0, 0, 0);
// get time in milliseconds
Long timeInmilliseconds = cal.getTimeInMillis();
// print time
Log.v("log", "Date "+ new Date(cal.getTimeInMillis()));
}
Also see this:
A common mistake is to implicitly use the default locale when producing output meant to be machine-readable. This tends to work on the developers test devices (especially because so many developers use en_US), but fails when run on a device whose user is in a more complex locale.
For example, if you are formatting integers some locales will use non-ASCII decimal digits. As another example, if you are formatting floating-point numbers some locales will use ',' as the decimal point and '.' for digit grouping. That is correct for human-readable output, but likely to cause problems if presented to another computer (parseDouble(String) cannnot parse such a number, for example).
Related
I have a textview and when I click on it, datepicker dialog opens up. I am trying to display today's date on the datepicker dialog. If today is October 11, 2021, the datepicker dialog shows Novermber 11, 2021. But when I select the dates, the textview shows the correct date which is October 11, 2021. The problem is the month which is for some reason up by one.
public View.OnClickListener openDatePicker = new View.OnClickListener() {
#Override
public void onClick(View view) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
String todaysDate = LocalDate.now().toString();
Log.i("todays date", todaysDate);
LocalDate localDate = LocalDate.parse(todaysDate, formatter);
openDatePickerForParty(localDate);
}
};
public void openDatePickerForParty(LocalDate givenLocalDT){
DatePickerDialog startDateDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
AddNewEventScreen.this.textViewEventDate.setText(year + "-"+ (month) + "-" + day);
}
}, givenLocalDT.getYear(), givenLocalDT.getMonthValue(), givenLocalDT.getDayOfMonth());
Log.i("thismonth", String.valueOf(givenLocalDT.getMonthValue()));
startDateDialog.show();
}
The Log "thismonth" also displays the correct month of 10.
The reason for confusion here is the fact that DatePickerDialog widget accepts month value from 0 to 11.
monthOfYear -----> int: the initially selected month of the year (0-11 for compatibility with Calendar#MONTH)
So when you pass 10 for October for it its November. Just subtract the month value by 1 before initializing the DatePickerDailog and then its all fine. More info here
I am trying to update system time and date. Setting time works fine as i have system permissions in my app and application is signatured as system app also setting date works fine for Months Jan upto Nov, but when i select December as month it is setting month to Jan. this all is cause of i am adding 1 to month but in a case i dont add 1 it creates problem for every month. if I select Dec it is Showing Nov, if I am selecting Jan it works fine , When I select Feb it again selects Jan, If I select March it selects Feb. every time it is setting one month less than the selected one.
here is my code
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minutes) {
mHour = hourOfDay;
mMinute = minutes;
Calendar c = Calendar.getInstance();
c.set(mYear, mMonth+1, mDay, mHour, mMinute);
Intent intent = new Intent();
intent.setAction(Action);
intent.putExtra("time", c.getTimeInMillis());
getContext().sendBroadcast(intent);
}
};
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
mYear = arg1;
mMonth = arg2;
mDay = arg3;
mTimePickerDialog.show();
}
};
at the other end
long when = intent.getLongExtra("time", -1);
if (DEBUG)
Log.i(TAG, "Incoming time: " + when);
if (when / 1000 < Integer.MAX_VALUE) {
SystemClock.setCurrentTimeMillis(when);
}
Time time = new Time();
TvManager tvmng = TvManager.getInstance();
TimerManager timerMgr = null;
if(tvmng!=null)
timerMgr = tvmng.getTimerManager();
time.set(when);
try {
timerMgr.setClkTime(time, true);
} catch (TvCommonException e) {
e.printStackTrace();
}
Please correct the code as mentioned below.
Calendar c = Calendar.getInstance();
c.set(mYear, mMonth, mDay, mHour, mMinute);
remove the +1 you added after the month.
When you set the month in calender than it should be between 0 to 11 when you pass month +1 and your month is 11 then it will be 11+1 =12 and calender consider it as Jan not December.
When you use the date selected for the purpose of showing to user then you have to add month+1 so it will show exact month ,
But when you pass it to calender again for the purpose of storing users selection store it as it is without adding +1 if you added it before then make it month-1 and then add to calender object.
It should work as you expected.
Also look at my solution to over come the issue.
to get formatted date to display user
public static String getDate(Calendar calendar){
String formattedDate;
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy");
formattedDate=format.format(calendar.getTime());
return formattedDate;
}
To set date to calender instance after selecting date from date picker use it like below.
DialogFragment newFragment = new DatePickerDialogFragment() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
super.onDateSet(datePicker, year, month, day);
Calender curDateInstance=Calender.getInstance();
curDateInstance.set(Calendar.YEAR, year);
curDateInstance.set(Calendar.MONTH, month);
curDateInstance.set(Calendar.DAY_OF_MONTH, day);
txtPickUpDate.setText(DateUtils.getDate(curDateInstance));
}
};
I am using the example from the documentation.
From the method
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
I want the string "Mon, Sep 14, 2014". How do I get it? Ideally I really want "Mon, Sep 14, 2014 10:30PM" but I can't find a combined date and time picker.
Here ya go date time combined.
This is no meant to be mean just that you said you were having trouble finding one.
how to find it : http://bit.ly/1doSxEf
Which one I use:
https://github.com/bendemboski/DateSlider
// try this way
public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {
Time chosenDate = new Time();
chosenDate.set(dayOfMonth, monthOfYear, year);
long dt = chosenDate.toMillis(true);
CharSequence strDate = DateFormat.format("KKK MMM dd,yyyy", dt);
// mow use strDate..
}
I'm working on a registration form that has a date picker. When a user selects a date, a TextView updates showing the selected date in the format (MM-dd-YYYY). When the user clicks the submit button it passes the forms data into a mysql db. It obviously doesn't insert the date because its not in the proper format of (yyyy-MM-dd). I tried using SimpleDateFormat method, but cannot get it to work. Can someone help me understand how to format the date?
datedob = (TextView) findViewById(R.id.reg_dob);
String dob = datedob.getText().toString();
My datepicker code:
public void populateSetDate(int year, int month, int day) {
datedob = (TextView)findViewById(R.id.reg_dob);
datedob.setText(month + "-" + day + "-" + year);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}
}
You would need two DateFormat instances:
one to parse the date string from your TextView.
one to format the parsed date to the desired representation.
That would look somewhat like this, assuming your TextView contains a "MM-dd-yyyy" formatted representation of the selected date:
String dobSource = datedob.getText().toString();
Date dobDate = new SimpleDateFormat("MM-dd-yyyy").parse(dobSource);
String dobTarget = new SimpleDateFormat("yyyy-MM-dd").format(dobDate);
You can potentially avoid converting the date string from the TextView by keeping track of a Date or Calendar reference that is updated whenever onDateSet(...) gets hit. That instance would then effectively become the data model backing the TextView and the value that ends up being inserted into the database.
That being said, personally I prefer to store/persist dates in their most elementary representation: as a long value. Such values are usually more easy to work with (as you avoid any parsing) and generally better interchangeable between various platforms. In the end, storing a date should be all about the actual data - any specific representation/format only complicates things further down the road.
I'd like to get day, month and year values for save to db. These are my codes:
Declaretions:
private TextView tv_purchase_date;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
OnClickListener listener_show_dlg = null;
OnDateSetListener listener_mdate_display = null;
Event Code:
listener_show_dlg = new OnClickListener() {
public void onClick(View v) {
Calendar cal=Calendar.getInstance();
DatePickerDialog datePickDlg = new DatePickerDialog(
ItemsAddActivity.this,
listener_mdate_display,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
);
datePickDlg.show();
};
};
listener_mdate_display = new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mMonth = month;
mYear = year;
mDay = dayofMonth;
tv_purchase_date.setText(dayOfMonth + "/" + monthOfYear + "/" + year);
}
};
}
I try to store mMonth, mYear and mDay values in db. What is the best store type? as integer or as string??
I store in the DB one number that represents the date. It is the number of seconds that have passed since the beginning of the modern era (Jan 1, 1970.) From the Date Picker, you can get the M D Y values like this:
datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int yearOfYear,
int monthOfYear, int dayOfMonth) {
// the user has picked these values
year = yearOfYear;
month = monthOfYear;
day = dayOfMonth;
Then, I turn these into a single Date object like this.
Calendar cal = new GregorianCalendar(year, month, day);
Date dateOfGames = cal.getTime();
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
String cs = df.format(dateOfGames);
changeDateButton.setText(cs); // update the interface
}
};
before I put it in the DB, I turn it into a numebr of seconds like this:
long seconds = date.getTime() / 1000; // this is the date in seconds since the start of the epoch
....
when I take that single number of seconds out of the DB, and want it to be a Date object again, I do this:
date = new Date(seconds * 1000); // converting seconds to a Date object
You can use a DateFormat object to display the date object how you like to see it.
I know this is awkward. Since SQLite doesn't allow you to store a Date, the answer is going to be awkward. Perhaps there is a cleaner way than this, and others will recommned something. :)
I struggled with this issue for a while. I don't konw of anything better than this.
I stored the date in the DB as a single long int. It is pretty easy to convert your Date to the number of seconds since the epoch (Jan 1, 1970), and it is also easy to convert the number of seconds into a Date object.
You need to be careful with seconds and milliseconds.
date = new Date(seconds * 1000); // converting seconds to a Date
seconds = date.getTime() / 1000; // this is the date in seconds since the start of the epoch
// Use Greg calendar to get a Date object from day, month, year
Date dateOfGames = new GregorianCalendar(year, month, day).getTime();
Does that help at all?
I created sqllite table with this sql string:
create table items (id INTEGER PRIMARY KEY AUTOINCREMENT, pdate DATE)
I writed some methods to convert date:
public String date_to_str(Date date) {
String pattern = "dd.MM.yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
Log.d(_watcher_name, "date_to_str" + dateFormat.format(date));
return dateFormat.format(date);
}
public Date mdy_to_date (int day, int month, int year) {
Calendar cal = new GregorianCalendar(year, month, day);
return cal.getTime();
}