I am using Material DateTime picker for choosing date and time. Its working fine, but in onTimeSetListener method it returns hourOfTheDay in 24 hours format.
I want to show it it 12 hour format for that I used the if condition where hours are greater than 12 then it should show PM, but the hour number dose not change.
How can I change this?
public class TransportFragment extends Fragment implements DatePickerDialog.OnDateSetListener,TimePickerDialog.OnTimeSetListener {
private OnFragmentInteractionListener mListener;
private EditText mEditTxt_From,mEditTxt_To,mEditTxt_DateTime;
int PLACE_PICKER_REQUEST = 1;
private static final String TAG = "PlacePickerSample";
private static final int REQUEST_PLACE_PICKER_FROM = 1;
private static final int REQUEST_PLACE_PICKER_TO = 2;
private String mDate;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_transport, container, false);
mEditTxt_From = (EditText) view.findViewById(R.id.editTextFrom);
mEditTxt_To = (EditText) view.findViewById(R.id.editTextTo);
mEditTxt_DateTime = (EditText) view.findViewById(R.id.editTextDateTime);
mEditTxt_DateTime = (EditText) view.findViewById(R.id.editTextDateTime);
mEditTxt_DateTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar now = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog.newInstance(
TransportFragment.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.setVersion(DatePickerDialog.Version.VERSION_2);
dpd.setAccentColor(ContextCompat.getColor(getActivity(),R.color.colorAccent));
dpd.show(getFragmentManager(), "Datepickerdialog");
}
});
#Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
mDate = dayOfMonth+"/"+(++monthOfYear)+"/"+year;
Calendar now = Calendar.getInstance();
TimePickerDialog tpd = TimePickerDialog.newInstance(
TransportFragment.this,
now.get(Calendar.HOUR_OF_DAY),
now.get(Calendar.MINUTE),
false
);
tpd.setVersion(TimePickerDialog.Version.VERSION_2);
tpd.setAccentColor(ContextCompat.getColor(getActivity(),R.color.colorAccent));
tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
Log.d("TimePicker", "Dialog was cancelled");
}
});
tpd.show(getFragmentManager(), "Timepickerdialog");
}
#Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
String hourString = hourOfDay < 10 ? "0"+hourOfDay : ""+hourOfDay;
String minuteString = minute < 10 ? "0"+minute : ""+minute;
String secondString = second < 10 ? "0"+second : ""+second;
String time;
if(hourOfDay > 12)
{
time = hourOfDay + ":" + minuteString + " PM";
}
else {
time = hourOfDay + ":" + minuteString + " AM";
}
mEditTxt_DateTime.setText(mDate + " " + time );
}
}
Please help. Thank you.
I think your if statement is invalid:
if (hourOfDay > 12) {
time = (hourOfDay - 12) + ":" + minuteString + " PM";
} else {
...
}
You do not need to reinvent the wheel. In particular, if your app is working with dates and times, you should consider getting the ThreeTenABP library and using the modern Java date and time classes. One of these, LocalTime, solves your task in two lines:
DateTimeFormatter twelveHourTimeFormatter
= DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.ENGLISH);
String time = LocalTime.of(hourOfDay, minute, second)
.format(twelveHourTimeFormatter);
Once you move to Java 8 the classes are built-in and you can discard the library.
In case you don’t want the dependency on one more external library, you can obtain the same with the outdated classes GregorianCalendar, Date and SimpleDateFormat, only it will be less elegant and far from future-proof.
Links
ThreeTenABP
Question: How to use ThreeTenABP in Android Project
Related
I want change the month and year with these two numberpickers but I do not know how to change the date. What I want to do is this: when i click on OK button on BottomSheetDialog I want to set the month and year. Can you help me please? I tried but I couldn't find any solution on the internet. If you help me, I'll be appreciated. Thank you.
public class PlannerFragment extends Fragment implements CalendarAdapter.OnItemListener{
private TextView monthYearTextView;
private TextView monthYearPickerOKTextView;
private ImageView nextMonthImageView, previousMonthImageView;
private RecyclerView calendarRecyclerView;
private LocalDate selectedDate; /// tekrar buna bakılacak
private NumberPicker monthNumberPicker, yearNumberPicker;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().setTitle("Planner");
View v = inflater.inflate(R.layout.fragment_planner, container, false);
previousMonthImageView = v.findViewById(R.id.previous_month_image_view);
nextMonthImageView = v.findViewById(R.id.next_month_image_view);
calendarRecyclerView = v.findViewById(R.id.calendar_recycler_view);
monthYearTextView = v.findViewById(R.id.month_year_text_view);
selectedDate = LocalDate.now();
setMonthYear();
previousMonthImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDate = selectedDate.minusMonths(1);
setMonthYear();
}
});
nextMonthImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDate = selectedDate.plusMonths(1);
setMonthYear();
}
});
monthYearTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
monthYearPicker(v);
}
});
return v;
}
private void setMonthYear() {
monthYearTextView.setText(monthYearFromDate(selectedDate));
ArrayList<String> daysInMonth = daysInMonthArray(selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(getActivity(), daysInMonth,
this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
private ArrayList<String> daysInMonthArray(LocalDate date) {
ArrayList<String> daysInMonthList = new ArrayList<>();
YearMonth yearMonth = YearMonth.from(date);
int daysInMonth = yearMonth.lengthOfMonth();
LocalDate firstDayOfMonth = selectedDate.withDayOfMonth(1);
int dayOfWeek = firstDayOfMonth.getDayOfWeek().getValue();
if (dayOfWeek == 7){
dayOfWeek = 1;
} else {
dayOfWeek++;
}
for (int i = 1; i <= 42; i++) {
if (i < dayOfWeek || i >= daysInMonth + dayOfWeek){
daysInMonthList.add("");
} else {
daysInMonthList.add(String.valueOf(i - dayOfWeek + 1));
}
}
return daysInMonthList;
}
private String monthYearFromDate(LocalDate localDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
return localDate.format(formatter);
}
#Override
public void onItemClick(int position, String dayText) {
LocalDate firstDayOfMonth = selectedDate.withDayOfMonth(1);
int dayOfWeek = firstDayOfMonth.getDayOfWeek().getValue();
if (dayOfWeek == 7){
dayOfWeek = 1;
} else {
dayOfWeek++;
}
if (!dayText.equals("")){
/*Toast.makeText(getActivity(), dayText + " " + monthYearFromDate(selectedDate),
Toast.LENGTH_SHORT).show();*/
Toast.makeText(getActivity(), String.valueOf(dayOfWeek),
Toast.LENGTH_SHORT).show();
}
}
public void monthYearPicker(View v){
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(getActivity(),
R.style.BottomSheetDialogTheme);
View bottomSheetView = LayoutInflater.from(getActivity())
.inflate(R.layout.month_and_year_picker_bottom_sheet_layout,
(ConstraintLayout) v.findViewById(R.id.month_year_picker_bottom_sheet_container));
monthNumberPicker = bottomSheetView.findViewById(R.id.month_number_picker);
yearNumberPicker = bottomSheetView.findViewById(R.id.year_number_picker);
final Calendar calendar = Calendar.getInstance();
Month.initMonths();
monthNumberPicker.setMinValue(0);
monthNumberPicker.setMaxValue(Month.getMonthArrayList().size() - 1);
monthNumberPicker.setDisplayedValues(Month.monthNames());
monthNumberPicker.setValue(calendar.get(Calendar.MONTH));
yearNumberPicker.setMinValue(1984);
yearNumberPicker.setMaxValue(2040);
yearNumberPicker.setValue(calendar.get(Calendar.YEAR));
bottomSheetView.findViewById(R.id.month_year_picker_ok_text_view).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetDialog.dismiss();
selectedDate.withMonth(monthNumberPicker.getValue());
setMonthYear();
Toast.makeText(getActivity(), Month.getMonthArrayList().get(monthNumberPicker.getValue()).getName(),
Toast.LENGTH_SHORT).show();
}
});
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
}
}
Good implementation, proper updated answer:
LocalDate date1 = LocalDate.of(2021, Month.JANUARY, 1);
LocalDate date2 = date1.withYear(2010);
LocalDate date3 = date2.withMonth(Month.DECEMBER.getValue());
LocalDate date4 = date3.withDayOfMonth(15);
LocalDate date5 = date4.with(ChronoField.DAY_OF_YEAR, 100);
Stolen from https://kodejava.org/how-do-i-manipulate-the-value-of-localdate-object/
Bad outdated implementation, bad answer (just here for protocol)
Simple pure Java implementation:
Use Calendar. Create a new instance; you probably want Gregorian Calendar: Calendar.getInstance();
Set the calendar value to the date: cal.setTime(pDate);
adjust single fields: cal.add(pField, pValue); or cal.set(pField, pValue);
retrieve Date object: cal.getTime();
You could also use the new java.time package, with classes like LocalDateTime etc.
And then there's a myriad of Java Date Time libraries out there.
Choose the way that works best for you.
I have this code, I want to add 40 weeks to the date I get from the date Picker and get the new date after the 40 weeks (280 days) has been added to the date from the date picker.
Code:
public class MainActivity extends AppCompatActivity {
DatePickerDialog picker;
EditText eText;
Button btnGet;
TextView tvw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
eText=(EditText) findViewById(R.id.editText1);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
eText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvw.setText("Selected Date: "+ eText.getText());
}
});
}
}
Joda time is a very convenient library for handling such cases. Add this to your project:
dependencies {
compile 'joda-time:joda-time:2.10.2'
}
And then you can manipulate the dates like this:
DateTime dt = DateTime.now();
DateTime laterDate = dt.withYear(2020)
.withMonthOfYear(3)
.withDayOfMonth(14)
.plusWeeks(40);
Remember that in JodaTime date objects are immutable (which is a very good idea), so each manipulation produces a new object.
First, convert the current format to milliseconds and then add specific days milliseconds and then again get it in the desired format. Like this way:
new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(year,monthOfYear + 1,dayOfMonth);
long timeInMilliseconds =
calendar.getTimeInMillis()+TimeUnit.DAYS.toMillis(280);
calendar.setTimeInMillis(timeInMilliseconds);
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
eText.setText(mDay + "/" + mMonth + "/" + mYear);
}
}, year, month, day);
picker.show();
}
});
Use add(Calendar.DAY_OF_MONTH, int) function in this way:
cldr.add(Calendar.DAY_OF_MONTH, 280);
Logically speaking, you don't have to add 40 weeks per say, a week has specific number of days, thus you can just add 40*7 = 280 days in your current day picked up from date picker.
[current date] + TimeUnit.DAYS.toMillis(280)
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Date date = (Date) getArguments().getSerializable(ARG_DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = LayoutInflater.from(getActivity())
.inflate(R.layout.dialog_date, null);
mDatePicker = (DatePicker) v.findViewById(R.id.dialog_date_picker);
mDatePicker.init(year, month, day, null);
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
int year = mDatePicker.getYear();
int month = mDatePicker.getMonth();
int day = mDatePicker.getDayOfMonth();
Date date = new GregorianCalendar(year,
month, day).getTime();
sendResult(Activity.RESULT_OK, date);
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
}
I feel like getTime is what
My problem is, but I cant fix it
I just want to display the date
and not the time at all but it wont let me. It always comes back as MM DD nn hhmmss zzz. All I want is the time to be displayed. here is where I want to display it
private TextView mTitleTextView;
private TextView mDateTextView;
private Crime mCrime;
public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_crime, parent, false));
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return false;
}
});
mTitleTextView = (TextView) itemView.findViewById
(R.id.crime_tile);
mDateTextView = (TextView) itemView.findViewById
(R.id.crime_date);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getTitle());
mDateTextView.setText(mCrime.getDate().toString());
}
In my list view here it always shows the format with the time in it and I just want the day, month, day of month, and year. Not sure if this makes sense, but does anyone have any ideas?
This is how I handle dates:
public static String DATE_FORMAT_NOW="MMM d yyyy"
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
final Calendar cal = Calendar.getInstance();
final String timestamp = "Last Modified: " + sdf.format(cal.getTime());
You can change the DATE_FORMAT_NOW to your needs
This particular format will put the date as: Jul 15 2017
SimpleDateFormat might have a lint warning, you can add SuppressLint to it if you want. I've never had any issue doing it this way
I want to use the calendarDaysBetween() below method in my TextView, or I want my TextView to display difference of two dates. Can anyone help me with this?
public class MainActivity extends FragmentActivity {
static EditText metTodate, metFromdate, metInTime, metOutTime;
static long no_of_days1;
static long no_of_days2;
Button mbtnApplyLeave;
ImageView mivBack;
RadioButton halfday1, halfday2, first_half, second_half, first_half1, second_half1, full_day1, full_day2;
static TextView no_of_days;
static TextView no_of_days3;
public static String str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
metTodate = (EditText)findViewById(R.id.etTodate);
metFromdate = (EditText)findViewById(R.id.etFromdate);
metInTime = (EditText)findViewById(R.id.etInTime);
metOutTime = (EditText)findViewById(R.id.etOutTime);
mivBack = (ImageView)findViewById(R.id.ivBack);
halfday1 = (RadioButton)findViewById(R.id.halfday1);
halfday2 = (RadioButton)findViewById(R.id.halfday2);
first_half = (RadioButton)findViewById(R.id.firsthalf1);
second_half = (RadioButton)findViewById(R.id.secondhalf1);
first_half1 = (RadioButton)findViewById(R.id.firsthalf2);
second_half1 = (RadioButton)findViewById(R.id.secondhalf2);
full_day1 = (RadioButton)findViewById(R.id.fullday1);
full_day2 = (RadioButton)findViewById(R.id.fullday2);
no_of_days = (TextView)findViewById(R.id.etnoofdays);
// Here is my method where I want my text view to display dates.
no_of_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calendarDaysBetween(Calendar metFromdate, Calendar metTodate);
}
});
}
// Both date picker dialogs
public void showTruitonDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
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) {
// Do something with the date chosen by the user
metTodate.setText(day + "/" + (month + 1) + "/" + year);
}
}
public void showFromDatePickerDialog(View v) {
DialogFragment newFragment = new FromDatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public static class FromDatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c1 = Calendar.getInstance();
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
int day1 = c1.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day1);
// calendarDaysBetween(Calendar metFromdate, Calendar metTodate);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
metFromdate.setText(day + "/" + (month + 1) + "/" + year);
}
}
public static long calendarDaysBetween(Calendar metFromdate, Calendar metTodate) {
// Create copies so we don't update the original calendars.
Calendar start = Calendar.getInstance();
start.setTimeZone(metFromdate.getTimeZone());
start.setTimeInMillis(metFromdate.getTimeInMillis());
Calendar end = Calendar.getInstance();
end.setTimeZone(metTodate.getTimeZone());
end.setTimeInMillis(metTodate.getTimeInMillis());
// Set the copies to be at midnight, but keep the day information.
start.set(Calendar.HOUR_OF_DAY, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MILLISECOND, 0);
end.set(Calendar.HOUR_OF_DAY, 0);
end.set(Calendar.MINUTE, 0);
end.set(Calendar.SECOND, 0);
end.set(Calendar.MILLISECOND, 0);
// At this point, each calendar is set to midnight on
// their respective days. Now use TimeUnit.MILLISECONDS to
// compute the number of full days between the two of them.
no_of_days1 = TimeUnit.MILLISECONDS.toDays(Math.abs(end.getTimeInMillis() - start.getTimeInMillis()));
String finalresult = new Double(no_of_days1).toString();
no_of_days.setText(finalresult);
return no_of_days1;
}
}
try this
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date past = format.parse("05/06/2015");
Date now = new Date();
System.out.println(TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime()) + " minutes ago");
System.out.println(TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime()) + " hours ago");
System.out.println(TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime()) + " days ago");
It will give you difference in minute and hours also from current date, you can use your own date format and own date objects
You can use the following code to get a date difference in number of days.
public void calendarDaysBetween(Calendar metFromdate, Calendar etTodate)
{
long diff = (metFromdate.getTimeInMillis() - metTodate.getTimeInMillis());
long no_of_days1 = Math.abs(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
no_of_days.setText(no_of_days1+"");
}
First declear Calendar object
public Calendar metFromdate= Calendar.getInstance();
public Calendar metTodate== Calendar.getInstance();
Change first DatePicker values
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
metFromdate.set(Calendar.YEAR, year);
metFromdate.set(Calendar.MONTH, month);
metFromdate.set(Calendar.DAY_OF_MONTH, day);
}
change second DatePicker values
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
metTodate.set(Calendar.YEAR, year);
metTodate.set(Calendar.MONTH, month);
metTodate.set(Calendar.DAY_OF_MONTH, day);
}
change button click
no_of_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calendarDaysBetween(metFromdate, metTodate);
}
});
you used it
Calendar date1 = Calendar.getInstance(); Calendar date2 =
Calendar.getInstance();
date1.clear();
date1.set(datePicker1.getYear(),datePicker1.getMonth(),datePicker1.getDayOfMonth());
date2.clear();
date2.set(datePicker2.getYear(),datePicker2.getMonth(),datePicker2.getDayOfMonth());
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
float dayCount = (float) diff / (24 * 60 * 60 * 1000);
textView.setText(Long.toString(diff) + " " + (int) dayCount);
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
........
........
compile 'joda-time:joda-time:2.2'
}
and
public String getTimeAgo(long ago){
DateTime timeAgo = new DateTime(ago*1000L);
DateTime now = new DateTime();
Period period = new Period(timeAgo, now);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendYears().appendSuffix(" Years, ")
.appendMonths().appendSuffix(" Months, ")
.appendWeeks().appendSuffix(" Weeks, ")
.appendDays().appendSuffix(" Days, ")
.appendHours().appendSuffix(" Hours, ")
.appendMinutes().appendSuffix(" Minutes, ")
.appendSeconds().appendSuffix(" Seconds ago ")
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
return elapsed;
}
and
yourTextView.setText(getTimeAgo(long-your_past_date_millis));
I am doing datepicker. I am facing some challenges. I am checking wheather selected date is weekend or not. If it is weekend then it should give current date only. Now I don't know where should I put condition in this program and how to get the day of the week and against which thing I should check.
Please, help me.
// TimePickerDialog.OnTimeSetListener
{
//Declaration for class
ButtonViews views;
dpListener dpListenerView;
// Declartion for member vairables
int day, month, x_year;
int hour;
int minute;
Calendar calendar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
views = new ButtonViews();
dpListenerView = new dpListener();
//ButtonListener
views.button_date.setOnClickListener(this);
views.button_time.setOnClickListener(this);
//
// pick up the default date using Calender class
calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
curr_date();
hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);
setupDate(day, month, x_year);
setupTime(hour, minute);
}
public void curr_date(){
day = calendar.get(Calendar.DAY_OF_MONTH);
month = calendar.get(Calendar.MONTH);
x_year = calendar.get(Calendar.YEAR);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_date:
showDatePickerDialog();
break;
case R.id.button_time:
/* showTimePickerDialog();*/
break;
}
}
private void setupTime(int hours, int minutes) {
views.button_time.setText(hours + ":" + minutes);
}
private void setupDate(int day, int month, int year) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy");
String strMonth = ((month + 1) <= 9) ? ("0" + (month + 1)) : String.valueOf(month + 1);
views.button_date.setText(String.valueOf(day) + "/" + strMonth + "/" + String.valueOf(year));
String strDate = String.valueOf(day) + "/" + strMonth + "/" + String.valueOf(year);
Date d = null;
try {
d = (Date) sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
calendar.setTime(d);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if(dayOfWeek == 7 || dayOfWeek == 1) {
Toast.makeText(DateTimePickerActivity.this,"You have chosen weekend",Toast.LENGTH_SHORT);
}
}
private void showDatePickerDialog() {
DatePickerDialog datepickerdialog = new DatePickerDialog
(
this,
dpListenerView,
/* new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
} },*/
//this,
x_year,
month,
day
);
datepickerdialog.show();
}
class ButtonViews {
Button button_time;
Button button_date;
public ButtonViews() {
button_date = (Button) findViewById(R.id.button_date);
button_time = (Button) findViewById(R.id.button_time);
}
}
class dpListener implements OnDateSetListener {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
setupDate(dayOfMonth, monthOfYear, year);
/* if(dayOfWeek == 7 || dayOfWeek == 1) {*/
// as your requirement: you should display message they can not select the weekend" here
// then you set the value in datepickerdialog by current date
// Toast.makeText(DateTimePickerActivity.this
// , "You have selected weekend ", Toast.LENGTH_SHORT).show();
// }
}
}
}