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);
Related
I am new to Android.I have a requirement, I have a field to enter the Date Of Birth of a person.On successful selection I wanna return the total number of months from the DOB to current date.For example, if I entered DOB as 19/10/2012 I wanna return 36(months).I searched for this, but didn't find anything suitable to my requirement.Here is my current code which return sucessful data,
private void showDate(int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day);
Date date = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
if(System.currentTimeMillis() > date.getTime()) {
edtDate.setText(sdf.format(date));
LocalDate date1 = new LocalDate(date);
LocalDate date2 = new LocalDate(new java.util.Date());
PeriodType monthDay = PeriodType.yearMonthDayTime();
Period difference = new Period(date1, date2, monthDay);
int months = difference.getMonths();
months=months + 1;
System.out.println("16102015:Nunber of Months"+months);
}else{
Toast.makeText(mActivity,getResources().getString(R.string.date_validationmsg),Toast.LENGTH_LONG).show();
}
}
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);
int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
To start with, I'd suggest using LocalDate instead of DateTime for the computations. Ideally, don't use java.util.Date at all, and take your input as LocalDate to start with (e.g. by parsing text straight to that, or wherever your data comes from.) Set the day of month to 1 in both dates, and then take the difference in months:
private static int monthsBetweenDates(LocalDate start, LocalDate end) {
start = start.withDayOfMonth(1);
end = end.withDayOfMonth(1);
return Months.monthsBetween(start, end).getMonths();
}
UPDATE 1
see this link the OP is accepted the same answer because Months.monthsBetween() method is not working proper for him
UPDATE 2
LocalDate userEnteredDate = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(date));
LocaleDate currentDate = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
int months = monthsBetweenDates(userEnteredDate, currentDate)
Using Joda-time library here, I was able to get the desired result.
Try the below code it would give the desired the difference in months.
DateTime date1 = new DateTime().withDate(2012, 10, 19);
DateTime today = new DateTime().withDate(2015, 10, 19);
// calculate month difference
int diffMonths = Months.monthsBetween(date1.withDayOfMonth(1), today.withDayOfMonth(1)).getMonths();
Using JodaTime, it's really easy:
http://www.joda.org/joda-time/apidocs/
int nMonths = new Period(startTime, endTime).getMonths();
Use this code to calculate months between two dates
public static int monthsBetweenUsingJoda(Date d1, Date d2) {
return Months.monthsBetween(new LocalDate(d1.getTime()), new LocalDate(d2.getTime())).getMonths();
}
I'm using Parse as a data store for an app I'm building. I have a Date parameter within the class that stores the expiry date of a food that is saved to Parse. The date is inputted using a datepicker (code below)
The date picker is created as such:
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
expiry_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(AddItem.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
And the update label method converts it to a readable date and displayed in an EditText
private void updateLabel() {
String myFormat = "dd/MM/yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.UK);
EditText update = (EditText) findViewById(R.id.expiry_date);
update.setText(sdf.format(myCalendar.getTime()));
}
Then, when the date is saved, it converts in from a string to a date
String dateString = expiry_date.getText().toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
This displays the correct date, as I'd expect. When saved however, the date is incorrect. For example, if I chose 28/08/2015, it would be saved in the Parse core as 27/08/2015:2300. It always saves as the day before with 11pm appended to it.
I wouldn't mind a time being appended to the date, but I'd prefer it to be 11:59pm on the day I picked, so I can compare dates later.
When the dates are displayed, they actually display the correct date (as in, the one picked from the date picker), rather than the saved date in Parse.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date = sdf.format(Calendar.getInstance().getTime());
Date datecomp = new Date();
datecomp.getDate();
int check = object.getDate("expiry").compareTo(datecomp);
Format formatter = new SimpleDateFormat("dd/MM/yyyy");
I'm assuming this is something to do with the date conversion, but I can't figure out why it's doing this, and I've looked at a lot of different sources, but none seem to describe my problem. Any help would be much appreciated
Parse stores dates as GMT reference (not +3h or -2h GMT e.i someone from Turkey and someone from US have different time at the same moment.) So you should make localization on your application via keeping client timezone in parse db.
int offsetInMs = 3600000;
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
TimeZone timeZone = calendar.getTimeZone();
TimeZone gmt0 = timeZone.getTimeZone("GMT0");
TimeZone gmtNewYork = timeZone.getTimeZone("America/New_York");
TimeZone gmtLondon = timeZone.getTimeZone("Europe/London");
TimeZone gmtIstanbul = timeZone.getTimeZone("Asia/Istanbul");
TimeZone local = timeZone.getDefault();
System.out.println(gmt0.getID()+" -> "+gmt0.getOffset(date.getTime())/offsetInMs);
System.out.println(gmtNewYork.getID() + " -> " + gmtNewYork.getOffset(date.getTime())/offsetInMs);
System.out.println(gmtLondon.getID() + " -> " + gmtLondon.getOffset(date.getTime())/offsetInMs);
System.out.println(gmtIstanbul.getID() + " -> " + gmtIstanbul.getOffset(date.getTime())/offsetInMs);
System.out.println(local.getID()+ " -> " + local.getOffset(date.getTime())/offsetInMs);
i.e. Your local time zone is GMT+2 and local time is 15:00,
Parse save it as 13:00(GMT). You shoud create a column named GMTOffset which keeps GMT+2.
Results:
GMT0 -> 0, America/New_York -> -4, Europe/London -> 1, Asia/Istanbul -> 3, Asia/Istanbul -> 3
I think that Parse basetime is GMT0. Create a column named GMTOffset which keeps -4, 1, 3, 3 (user local offset).
Additionally, if you will use parse time in your application, Parse may localize time on the client side. Please check that also.
P.S. as my experience, client side time is not reliable, you should use your server(if exist) time.
During the signup process, I'm trying to implement a code that stores a date value into a string value in the following format: "dd-mm-yyyy".
So, on the onCreate() method part, I declared a DatePicker variable as follows:
DatePicker dob = (DatePicker) findViewById(R.id.dob);
And on the onClick() method part, I wrote a code to convert this DatePicker value into the String.
String entered_dob = dob.toString();
But later when I opened the database I found out that this only returns a value which looks nonsense. How should I implement in order to get what I wanted?
If you want to store your date as a String (which is not a good practice)
DatePicker datePicker ;
SimpleDateFormat dateFormatter ;
Date d ;
String entered_dob ;
datePicker = (DatePicker) findViewById(R.id.dob);
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth() + 1;
int year = datePicker.getYear()
d = new Date(year, month, day);
dateFormatter = new SimpleDateFormat("MM-dd-yyyy");
entered_dob = dateFormatter.format(d);
If you want to get the timestamp you can do it like this
Calendar calendar = new GregorianCalendar(year, month, day);
long enterded_dob_ts = calendar.getTimeInMillis();
I would recommend storing the timestamp.
Use the Calendar to create this value. This one you can easily store as long (or string if you really want this)
Checkout this Example
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.
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;