I am beginner coder, currently making a reminder app. So far this app does the following:
When you click the datetime picker it opens my custom datetime picker
You select the date and the time (that is at least 10 minutes from now and is in the next 30 days)
Date and time you selected displays in TextView field on screen
Since there is no datetime picker I made a custom one. I tried a number of approaches and this is the only one that worked for me. So now I have this problem - I want to display the date and the time format that is the same as the format on the phone - for USA it would be month/day/year and AM/PM, for Europe day/month/year and 24hr format. If there is no way to do this I would like to at least display the month name - like this 03 Mar. I used StringBuilder to append day, month and year. This can be confusing if the date is for example 02/03/2016. As for the time I am displaying 24 hour format with added "0" for one digit numbers.
As I said I am a beginner so I am having problems using examples like this with StringBuilder. I also tried this example instead of StringBuilder, but I got but I got incompatyble types error: required android.widget.TextView, found java.lang.String.
My current way of displaying the date and time is shown bellow in the "// Update date and time" section. The rest of the code is here for for reference for anyone who needs to create a custom datetime picker :)
private Button mPickDate;
private TextView mDateDisplay;
private TextView mTimeDisplay;
final Calendar c = Calendar.getInstance();
private int mYear = c.get(Calendar.YEAR);
private int mMonth = c.get(Calendar.MONTH);
private int mDay = c.get(Calendar.DAY_OF_MONTH);
private int mHour = c.get(Calendar.HOUR_OF_DAY);
private int mMinute = c.get(Calendar.MINUTE);
static final int TIME_DIALOG_ID = 1;
static final int DATE_DIALOG_ID = 0;
And the rest of the code:
//Update date and time
private void updateDate() {
mDateDisplay.setText(
new StringBuilder()
.append(mDay).append("/")
.append(mMonth + 1).append("/")
.append(mYear).append(" "));
showDialog(TIME_DIALOG_ID);
}
public void updateTime() {
mTimeDisplay.setText(
new StringBuilder()
.append(pad(mHour)).append(":")
.append(pad(mMinute)));
}
// Append 0 if number < 10
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
// Generate DatePickerDialog and TimePickerDialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDate();
}
};
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
Calendar c2 = Calendar.getInstance();
if (mYear == c2.get(Calendar.YEAR)
&& mMonth == c2.get(Calendar.MONTH)
&& mDay == c2.get(Calendar.DAY_OF_MONTH)
&& (mHour < c2.get(Calendar.HOUR_OF_DAY) || (mHour == c2.get(Calendar.HOUR_OF_DAY) && mMinute <= (c2.get(Calendar.MINUTE) + 10))
)
) {
Toast.makeText(SetDateTimeActivity.this, "Set time at least 10 minutes from now", Toast.LENGTH_LONG).show();
} else {
updateTime();
}
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
c.add(Calendar.MONTH, +1);
long oneMonthAhead = c.getTimeInMillis();
datePickerDialog.getDatePicker().setMaxDate(oneMonthAhead);
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
return datePickerDialog;
case TIME_DIALOG_ID:
TimePickerDialog timePickerDialog =
new TimePickerDialog(this,
mTimeSetListener, mHour, mMinute, false);
return timePickerDialog;
}
return null;
}
Thank you in advance :)
EDIT - the solution I used in my code:
// Update date and time
private void updateDate() {
c.set(mYear, mMonth, mDay);
String date = new SimpleDateFormat("MMM dd, yyyy").format(c.getTime());
mDateDisplay.setText(date);
showDialog(TIME_DIALOG_ID);
}
public void updateTime() {
c.set(mYear, mMonth, mDay, mHour, mMinute); // check why do I need to add year,month,day
String time = new SimpleDateFormat(" hh:mm a").format(c.getTime());
mTimeDisplay.setText(time);
}
You can change the format whatever you want example is in below.
String strCurrentDate = "Wed, 18 Apr 2012 07:55:29 +0000";
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss Z");
Date newDate = format.parse(strCurrentDate);
format = new SimpleDateFormat("MMM dd,yyyy hh:mm a");
String date = format.format(newDate);
Or your local format
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy HH:mm", Locale.getDefault());
String formatted = sdf .format(900000);
System.out.println(simpleDateFormat.parse(formatted));
or you can take year month day from calander and format it.
Calendar cal = Calendar.getInstance();
cal.get(Calendar.YEAR);
cal.get(Calendar.DAY_OF_MONTH);
cal.get(Calendar.MONTH);
String format = new SimpleDateFormat("E, MMM d, yyyy").format(cal.getTime());
you just change the format for whatever your format search usa date format an put it in
SimpleDateFormat("here").format(cal.getTime());
Related
I am using date picker in android studio which on default shows year 1990 so i set the date picker to the current time.On doing this the previous day, month and year disappears.
What i want is to set the date picker to current date but still has access to previous calendar.
java.util.Date currentTime = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentTime.getTime());
int Day = calendar.get(Calendar.DAY_OF_MONTH);
int Month = calendar.get(Calendar.MONTH);
int Year = calendar.get(Calendar.YEAR);
Edit_SelectDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dpd = new DatePickerDialog(PURCHASE.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int mDay, int mMonth, int mYear) {
calendar.set(Calendar.YEAR, mYear);
calendar.set(Calendar.MONTH, mMonth);
calendar.set(Calendar.DAY_OF_MONTH, mDay);
// Edit_SelectDate.setText(mDay + "/" + (mMonth + 1) + "/" + mYear);
Edit_SelectDate.setText(mYear + "/" + (mMonth + 1) + "/" + mDay);
}
}, Day, Month, Year);
dpd.getDatePicker().setMinDate(System.currentTimeMillis());
dpd.show();
}
});
i guess its about dpd.getDatePicker().setMinDate(System.currentTimeMillis());
you set minimum date to now (System.currentTimeMillis()), so you cant see past.
I am want to split the date like hour and minute. I have used this code in my Android app:
reminderTextField.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
new SingleDateAndTimePickerDialog.Builder(view.getContext())
.minutesStep(1)
.setDayFormatter(formatter)
.mainColor(view.getResources().getColor(R.color.colorPrimary))
.titleTextColor(Color.BLACK)
.displayListener(new SingleDateAndTimePickerDialog.DisplayListener() {
#Override
public void onDisplayed(SingleDateAndTimePicker picker) {})
.mustBeOnFuture()
.title("Set Reminder")
.listener(new SingleDateAndTimePickerDialog.Listener() {
#Override
public void onDateSelected(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
String reminderTime = formatter.format(date);
reminderTextField.setText(reminderTime);
}
}).display();
}
link
Use the Calendar Class to do it like :
java.util.Date date= new Date("Your date here");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH); // Month
int day = cal.get(Calendar.DAY_OF_MONTH); // Day
int year = cal.get(Calendar.YEAR); // Year
int hour = cal.get(Calendar.HOUR_OF_DAY); // Hour
int minute = cal.get(Calendar.MINUTE); // Minute
...
If you want more, you have all the class Calendar with the methods on Oracle documentation
Then it's up to you ;)
Tip : use System.out.println() method to see the results on the console and make sure it's what you want.
I want to let the user pick the date after today, as a remind date, how can I do it?Also, how can I put the theme inside these codes,because there is no button for the user to choose.
Here is my code combine with datapickerdialog and timepickerdialog:
private void setDateTimeField (){
DatePickerDialog datePickerDialog = new DatePickerDialog(this, new
DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int selectedYear, int selectedMonth, int selectedDate) {
year = selectedYear;
month = selectedMonth;
day = selectedDate;
timePicker();
date_time = year + "-" + (month + 1) + "-" + day;
}
},year, month, day);
final Calendar calendar = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.MONTH, mm);
cal.set(Calendar.DAY_OF_MONTH, dd);
cal.set(Calendar.YEAR, yy);
datePickerDialog.getDatePicker().setMinDate(cal.getTimeInMillis());
datePickerDialog.show();
}
private void timePicker(){
// Get Current Time
final Calendar c = Calendar.getInstance();
hours = c.get(Calendar.HOUR_OF_DAY);
minutes = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(this,new
TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int
minute) {
hours = hourOfDay;
minutes = minute;
modifytime.setText(date_time+" "+hourOfDay + ":" +
minute);
}
}, hours, minutes, false);
timePickerDialog.show();
}
If you like to set the current date as minimum date and no past days should be selectable, then below solution will works I believe
Calendar cal = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
//Min date setting part
cal.set(Calendar.MONTH, mm);
cal.set(Calendar.DAY_OF_MONTH, dd);
cal.set(Calendar.YEAR, yy);
//Replace your code mDatePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis()); with the below line
mDatePickerDialog.setMinDate(cal.getTimeInMillis());
Since you are allowing the user to select only future dates, you should not need to set Max date.
Complete Code sample for your reference -
private void showDateDailog() {
final DatePickerDialog datePickerDialog = new DatePickerDialog(getApplicationContext(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int selectedYear, int selectedMonth, int selectedDate) {
year = selectedYear;
month = selectedMonth;
day = selectedDate;
addtime.setText(new StringBuilder().append(year).append("/")
.append(month + 1).append("/").append(day));
}
}, year, month, day);
final Calendar calendar = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
//Min date setting part
cal.set(Calendar.MONTH, mm);
cal.set(Calendar.DAY_OF_MONTH, dd);
cal.set(Calendar.YEAR, yy);
datePickerDialog.setMinDate(cal.getTimeInMillis());
//Maximum date setting part, if you need (Else don't add it)
/*Calendar calen = Calendar.getInstance();
calen.set(Calendar.MONTH, mm);
calen.set(Calendar.DAY_OF_MONTH, dd);
calen.set(Calendar.YEAR, yy + 2);
datePickerDialog.setMaxDate(calen.getTimeInMillis());*/
datePickerDialog.show();
}
This question already has answers here:
TimePicker Dialog from clicking EditText
(10 answers)
Closed 5 years ago.
I want to let the user pick the date and the time, I've finished the date but I don't know how to write hours and minutes to let the user choose date and time.
Here is my setDateTimeField
private void setDateTimeField() {
DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int selectedYear, int selectedMonth, int selectedDate) {
year = selectedYear;
month = selectedMonth;
day = selectedDate;
addtime.setText(new StringBuilder().append(year).append("-")
.append(month + 1).append("-").append(day));
}
},year, month, day);
final Calendar calendar = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.MONTH, mm);
cal.set(Calendar.DAY_OF_MONTH, dd);
cal.set(Calendar.YEAR, yy);
datePickerDialog.getDatePicker().setMinDate(cal.getTimeInMillis());
datePickerDialog.show();
}
The DatePicker is ideal for year, month, and day, but if you want to also set hours and minutes, you will want to look into the TimePicker class. See the documentation link here for reference.
A Sample would look like this:
Calendar cal = Calendar.getInstance();
TimePickerDialog d = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
int hour = i;
int minute = i1;
//Utilize the fields here
}
}, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), false);
d.show();
Sorry for my english. I need to set time between 00:00:00 and 06:00:00, but my code doesn't work. I'm using joda library. My below method doesn't work, i can set time 14:00 or another, not not beetwen 00:00 and 6:00. What i'm doing wrong?
public void setTime(final TextView setText) {
String dateStart = "00:00:00";
String dateStop = "06:00:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
int mHour = Hours.hoursBetween(dt1, dt2).getHours() % 24;
int mMinute = Minutes.minutesBetween(dt1, dt2).getMinutes() % 60;
TimePickerDialog tpd = new TimePickerDialog(context,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
setText.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
}
}, mHour, mMinute, true);
tpd.show();
}catch(Exception e) {
Toast.makeText(getApplicationContext(), "Cant open time, sorry", Toast.LENGTH_SHORT).show();
Log.e("Time error", e.toString());
}
}
Have a look here, with mHour and mMinute, you are removing from the DatePicker the hours before 6:00:00; copying from the link here is the problem:
public TimePickerDialog (Context context, int themeResId,
TimePickerDialog.OnTimeSetListener listener, int hourOfDay, int
minute, boolean is24HourView)
Added in API level 1 Creates a new time picker dialog with the
specified theme.
Parameters:
context the parent context
themeResId the resource ID of the theme to apply to this dialog
listener the listener to call when the time is set
hourOfDay the initial hour
minute the initial minute
is24HourView Whether this is a 24 hour view, or AM/PM.
here it is, leave them t 0 and 0 if you want all hours and minutes in your picker
EDIT:
if you want to set time only between 0 and 6, look at this post