I have 2 android datepickers and I want to get the dayOfWeek in each date picker but I get only the initial calendar day even if I change it. How to set the clickListener? I would like to get the day of the week in dayOfWeek and dayOfWeek1 variables.
dpTake=(DatePicker) rootView.findViewById(R.id.dpTake);
dpDelivery=(DatePicker) rootView.findViewById(R.id.dpDelivery);
Date dt = new Date();
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
dpDelivery.updateDate(c.YEAR, c.MONTH, c.DAY_OF_MONTH);
c.add(Calendar.DATE, 1);
dt = c.getTime();
dpTake.setMinDate(dt.getTime());
CalendarView cv = dpTake.getCalendarView();
long current = cv.getDate();
cv.setDate(cv.getMaxDate(), false, true);
cv.setDate(current, false, true);
c.add(Calendar.DATE, 2);
dt = c.getTime();
dpDelivery.setMinDate(dt.getTime());
CalendarView cvDelivery = dpDelivery.getCalendarView();
current = cvDelivery.getDate();
cvDelivery.setDate(cv.getMaxDate(), false, true);
cvDelivery.setDate(current, false, true);
dayOfWeek1 = c.get(Calendar.DAY_OF_WEEK);
Try this code
DatePickerDialog dpd = DatePickerDialog.newInstance(
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
);
dpd.setAccentColor(Color.parseColor("#029789"));
dpd.setMinDate(Calendar.getInstance());
dpd.show(getActivity().getFragmentManager(), "Datepickerdialog");
Related
I have Calendar value which is from Date Picker and I want to convert this value to String format "yyyy-MM-dd"
This is my Date Picker code. I save the selected values to startYear, startMonth and startDay.
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
and then I tried to convert these values to String in this way. But the log result is 0002-12-31 not what I selected from Date Picker.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
Never use Calendar. That terrible class was supplanted years ago by the modern java.time classes.
LocalDate
Instead, use LocalDate for a date-only value with no time-of-day and no offset or time zone.
LocalDate x = LocalDate.now() ;
String output = x.toString() ;
Build from parts.
LocalDate x = LocalDate.of( y , m , d ) ;
Get parts.
int y = x.getYear() ;
int m = x.getMonthValue() ;
int d = x.getDayOfMonth() ;
If your code goes like this; the log shows the date value before picking any dates. So you see the value for year: 0, month: 0 and day:0 (which is shown as 0002-12-31). (Note that the code inside onDateSet() method runs asynchronously, when the user picks a date.)
int startYear, startMonth, startDay;
Calendar today = GregorianCalendar.getInstance();
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
// startYear, startMonth, startDay are not initialized yet and equal 0.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
Instead; if you try to convert your Date to String "after the values are set" (Shown below) .You can see it will be correctly converted.
int startYear, startMonth, startDay;
Calendar today = GregorianCalendar.getInstance();
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
//************************************************************
//Now we have the picked values.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
//************************************************************
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
Let's see the simple code to convert Date to String
Basic
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String strDate = dateFormat.format(date);
System.out.println("Converted String: " + strDate);
Advanced
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
System.out.println("Date Format with MM/dd/yyyy : "+strDate);
formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
strDate = formatter.format(date);
System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
strDate = formatter.format(date);
System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);
}
I have a project where in two buttons are there named from and todate.And I need to show the status of the project based on start and end Date after pressing the button refresh.The problem is that I want to get the selected date when I press from date and when I press toDate it allow user to select the date and from date should always be less than the todate
public void showDatePicker(final Button view1) {
// Get Current Date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
if (view1.getId() == R.id.to_date) {
if (fromDateData == null || "startfrom".equalsIgnoreCase(fromDateData) || fromDateData.isEmpty())
return;
final Calendar c = Calendar.getInstance();
String[] dates = fromDateData.split("-");
mYear = Integer.parseInt(dates[2]);
mMonth = Integer.parseInt(dates[1]) - 1;
mDay = Integer.parseInt(dates[0]);
c.set(Calendar.YEAR, mYear);
c.set(Calendar.MONTH, mMonth);
c.set(Calendar.DAY_OF_MONTH, mDay);
}
if (view1.getId() == R.id.to_date) {
if (fromDateData == null || "start from".equalsIgnoreCase(fromDateData) || fromDateData.isEmpty())
return;
final Calendar c = Calendar.getInstance();
String[] dates = fromDateData.split("-");
mYear = Integer.parseInt(dates[2]);
mMonth = Integer.parseInt(dates[1]) - 1;
mDay = Integer.parseInt(dates[0]);
c.set(Calendar.YEAR, mYear);
c.set(Calendar.MONTH, mMonth);
c.set(Calendar.DAY_OF_MONTH, mDay);
}
if (view1.getId() == R.id.from_date)
fromDateData=date;
else
toDateData = date;
view1.setText(date);
}
}, mYear, mMonth, mDay);
datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
if (view1.getId() != R.id.from_date)
datePickerDialog.getDatePicker().setMaxDate(c.getTimeInMillis()); datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
datePickerDialog.show();
}
I have created a DatePicker within my app. But the problem I am trying to overcome is how to take the picked date and store it in my database:
In my DB, the date field is set to TEXT
private int mYear, mMonth, mDay, mHour, mMinute;
#Override
public void onClick(View v) {
final Calendar calendar = Calendar.getInstance();
//Get the date
if (v == buttonDatePicker) {
mYear = calendar.get(Calendar.YEAR);
mMonth = calendar.get(Calendar.MONTH);
mDay = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
etDate.setText(dayOfMonth + "-" + month + "-" + year);
mYear = year;
mMonth = month;
mDay = dayOfMonth;
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
//Get the time
if (v == buttonTimePicker) {
mHour = calendar.get(Calendar.HOUR_OF_DAY);
mMinute = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
etTime.setText(hourOfDay + ":" + minute);
mHour = hourOfDay;
mMinute = minute;
}
}, mHour, mMinute, true);
timePickerDialog.show();
}
}
I tried to convert the picked Year etc from int to String but it does not seem to like it when I tried to cast it.
How I am trying to store it in my DB :
typedUpSmsMessage = smsMessage.getText().toString();
ContentValues cv = new ContentValues();
cv.put("textMessage", typedUpSmsMessage);
cv.put("dateToSendText",mYear + mMonth + mDay);
cv.put("gameID", gameID);
automateGameDB.insert("automateGames", null, cv);
But ofcourse since the date is in int, it just adds the numbers.
Need to convert them into a string, or a date format? (yyyy-mm-dd hh-mm-ss)?
Thanks
Since the field is Text you should use cv.put("dateToSendText", year + "-" + month + "-" + dayOfMonth) with 4 digit year and 2 digit month and dayOfMonth, because it is comparable and sortable.
Insert your date in database like
cv.put("dateToSendText",dayOfMonth + "-" + month + "-" + year)
or
cv.put("dateToSendText",etTime.gettext().tostring());
Really don't understand your requirement.
Will this code
String string = Integer.toString(int); or String.valueOf(int) or simply string+""
solve your problem?
I advise you to store Date as a timestamp in your database :
Calendar calendar = Calendar.getInstance()
calendar.set(year, month, day, hour, minute, second)
Long timestamp = calendar.getTimeInMillis() // Save timestamp in database
Use
inputDate = mYear +"-"+ mMonth +"-"+ mDay;
SimpleDateFormat src = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
SimpleDateFormat dest = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.US);
Date date = null;
try {
date = src.parse(inputDate);
} catch (ParseException e) {
Log.d("Exception",e.getMessage());
}
String formattedDate = dest.format(date);
You can change dest Dateformat as u want...
Use 'TEXT' datatype in sqlite to store this date field
I want interval date. Whatever user enter date from date picker and from this date I want to get after one month date Suppose 1 Aug 2014 -> Output will be 1 September 2014.Can someone help me .Thanks to appreciate.
Hare is my Activity code
{
// Get current date by calender
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Month is 0 based, just add 1
etReplacementDate.setText(new StringBuilder()
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
etReplacementDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showDialog(DATE_OF_REPLACEMENT);
}
});
String fixedDate = etReplacementDate.getText().toString().trim();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try
{
convertedDate = dateFormat.parse(fixedDate);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Date Consersion = " + convertedDate);
/****************ReplaceMent Date***************************************************/
cal2.add(Calendar.getInstance(convertedDate), 30);
Date date_30dayslater = cal2.getTime();
System.out.println("date_30dayslater : " + date_30dayslater);
/****************Interval Date***************************************************/
String _30daysLater_String = new SimpleDateFormat("yyyy-MM-dd").format(date_30dayslater);
etNextReplanishmentDate.setText(_30daysLater_String);
System.out.println("30 days later: " + _30daysLater_String);
System.out.println("______________________________________");
/****************Before Date***************************************************/
cal2.add(Calendar.DATE, -1);
Date beforDate = cal2.getTime();
String beforDate_String = new SimpleDateFormat("yyyy-MM-dd").format(beforDate);
System.out.println("beforDate_String: " + beforDate_String);
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DATE_OF_REPLACEMENT:return new DatePickerDialog(this, pickerListenerReplacement, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListenerReplacement = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
etReplacementDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
}
What you want to do is add() one Calendar.MONTH to a date that you've gotten and parsed, etc. so I won't go into that. I'll assume you are handling everything correctly up to the point where you'd like to get the same day, if possible, of the next month.
Part of your problem, as your comment suggests, is Calendar.getInstance() does not have an implementation that takes a Date. But more importantly you don't need it. You have a Date and a Calendar instance and it seems like you're changing c2 anyway so why not use Calendar's setTime() method like this?
// setting c2 with the convertedDate then adding a month
c2.setTime(convertedDate);
c2.add(Calendar.MONTH, 1);
// Simple example
public static void main(String...args) {
Date d = new Date();
Calendar c = Calendar.getInstance();
c.setTime(d);
System.out.println(c.getTime());
c.add(Calendar.MONTH, 1);
System.out.println(c.getTime());
}
try to use this.
Calendar c = Calendar.getInstance();
int month = c.get((Calendar.MONTH));
c.set(Calendar.MONTH, month + 1);
long time = c.getTimeInMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String result = sdf.format(new Date(time1));
i want to make a list of dates between the given date range like--
ex: fromDate - 15/10/2013 and toDate - 15/12/2013
now the list should be
[ 15/10/2013, 31/10/2013, 1/1/2013, 30/11/2013, 1/12/2013, 15/12/2013 ]
i have written this code ---
private List<Date> datesList = new ArrayList<Date>();
public void findLastDate(){
Date lastDateOfMonth;
Date firstDateOfNextMonth = null;
datesList.add(fromDate);
do {
Calendar calendar = Calendar.getInstance();
if(firstDateOfNextMonth == null){
calendar.setTime(fromDate);
} else {
calendar.setTime(firstDateOfNextMonth);
}
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
lastDateOfMonth = calendar.getTime();
datesList.add(lastDateOfMonth);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(lastDateOfMonth);
calendar2.add(Calendar.MONTH, 1);
calendar2.set(Calendar.DAY_OF_MONTH, 1);
calendar2.add(Calendar.DATE, 0);
firstDateOfNextMonth = calendar2.getTime();
datesList.add(firstDateOfNextMonth);
} while(firstDateOfNextMonth.compareTo(toDate) < 0);
datesList.add(toDate);
System.out.println("List of dates " + datesList);
}
but i am getting a list as
[15/10/2013, 31/10/2013, 1/1/2013, 30/11/2013, 1/12/2013, 30/12/2013, 1/1/2014, 15/12/2013]
the dates 30/12/2013, 1/1/2014 should not be in the list so what should be the condition in while loop i am not getting it plz help me out...
Basically, you should be doing 2 things.
After you add a value to the Calendar, you need to be checking to see if that is now after the end time and
Unless it's equal to the end time, removing the last date from the list
For Example
List<Date> dates = new ArrayList<>(25);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, 15);
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.YEAR, 2013);
Calendar endCal = Calendar.getInstance();
endCal.set(Calendar.DATE, 15);
endCal.set(Calendar.MONTH, 11);
endCal.set(Calendar.YEAR, 2013);
dates.add(cal.getTime());
while (cal.before(endCal)) {
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
dates.add(cal.getTime());
if (cal.before(endCal)) {
cal.add(Calendar.DATE, 1);
dates.add(cal.getTime());
}
}
dates.remove(dates.size() - 1);
dates.add(endCal.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
for (Date d : dates) {
System.out.println(sdf.format(d));
}
Will output
15/10/2013
31/10/2013
01/11/2013
30/11/2013
01/12/2013
15/12/2013
Updated with example, based on original code
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, 15);
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.YEAR, 2013);
Date fromDate = cal.getTime();
Calendar endCal = Calendar.getInstance();
endCal.set(Calendar.DATE, 15);
endCal.set(Calendar.MONTH, 11);
endCal.set(Calendar.YEAR, 2013);
Date toDate = endCal.getTime();
List<Date> datesList = new ArrayList<>(25);
datesList.add(fromDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(fromDate);
do {
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
if (calendar.getTime().before(toDate)) {
datesList.add(calendar.getTime());
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, 0);
if (calendar.getTime().before(toDate)) {
datesList.add(calendar.getTime());
}
}
} while (calendar.getTime().before(toDate));
datesList.add(toDate);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
for (Date d : datesList) {
System.out.println(sdf.format(d));
}
Which outputs...
15/10/2013
31/10/2013
01/11/2013
30/11/2013
01/12/2013
15/12/2013
Note: The one thing that neither of these code snippets are doing is check to see if the last date in the list is actually the end date (although from the looks of it, yours seems to be able to get around this need)