Format Date into mysql format - android

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.

Related

How to save a Date from DatePicker into SQLite with Android Studio

I have a SQLite DB for my Android app project and I would like to save a date from a Date Picker.
TO be as efficient as possible, I cannot insert that date as a String.
So I'm trying to save my date as an Integer or a Long but I check all around the web and nothing clear enough to help me...
Here is my code:
public DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the chosen date
TextView dateView = (TextView) findViewById(R.id.newdatepicked);
// Create a Date variable/object with user chosen date
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day, 0, 0, 0);
Date date = cal.getTime(); // CAN I USE THIS LINE?
// Format the date using style MEDIUM and FR locale
DateFormat df_date = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
String dateDF= df_date.format(dateDF);
// Display the formatted date
dateView.setText(dateDF);
}
};
And my code to insert all my data:
public void SaveAlert(View v) {
String Article = tvArticle.getText().toString();
long DateEntree = calendar.getTimeInMillis(); // This line is working very well
long DateSortie = ;///////// I CANNOT FIND OUT HOW TO HANDLE THIS ...
My issue is with DateSortie.
Please let me apologize for my English and thanks a lot for your help
you can still store it as string and then retrieve them using the format you want for example
Calendar calendar = Calendar.getInstance();
/* to display time*/
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm");
/* to display date in the given format */
DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
/*get the date using */
Date dDate = dateFormatter.parse(yourObject.getTaskDate());
/*set the date */
calendar.setTime(dDate);

Best way to store date and time in Sqlite database in Android to perform date operations easily

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.

Date format issue in android when locale is arabic

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).

Android CalendarView: How do I get the date in correct format?

The past few days I've been searching for ways to get a 'readable' date out of my calendarview from android 4.0. I can't manage to find a solution or example that suits my problem. I did get it in miliseconds but not in a date format.
My problem is: I have a calendarview and I want the selected date by the user, shown in logcat in a dateformat yy-mm-dd.
I was used to the datepicker from android 2.2 and I'm not familiar with calendarview and can't find much about it either. Does anyone know a solution for this?
Okay so here is how to do this. When you fire your calendarview activity or a calendarview inside your activity it sets the date to the current date(meaning today). To get this current date just use the Calendar object provided by the java api to get this date example below:
Calendar date = Calendar.getInstance();
// for your date format use
SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
// set a string to format your current date
String curDate = sdf.format(date.getTime());
// print the date in your log cat
Log.d("CUR_DATE", curDate);
to get a date changed you must do this
CalendarView myCalendar = (CalendarView) findViewById(R.id.myCalenderid);
myCalendar.setOnDateChangeListener(myCalendarListener);
OnDateChangeListener myCalendarListener = new OnDateChangeListener(){
public void onSelectedDayChange(CalendarView view, int year, int month, int day){
// add one because month starts at 0
month = month + 1;
// output to log cat **not sure how to format year to two places here**
String newDate = year+"-"+month+"-"+day;
Log.d("NEW_DATE", newDate);
}
}
kandroidj's answer helps to create date, but not date of correct format.
So to format selected date:
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month,
int dayOfMonth) {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, dayOfMonth);
String sDate = sdf.format(calendar.getTime());
Log.d(TAG, "sDate formatted: " + sDate);
}
});
You should use SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String selectedDate = sdf.format(new Date(calendar.getDate()));
long date = calenderView.getDate();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date);
int Year = calendar.get(Calendar.YEAR);
int Month = calendar.get(Calendar.MONTH);
int Day = calendar.get(Calendar.DAY_OF_MONTH);
//customize According to Your requirement
String finalDate=Year+"/"+Month+"/"+Day;

How to get day, month and year from DatePickerDialog?

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();
}

Categories

Resources