How to get date from Calendar [duplicate] - java

This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Closed 5 years ago.
I have another class which showing calendar to user and setup date in textview. But how to get date (year from here? for calculate how old year user in general).
This is code which I'm using. This is: TextViewDatePicker editTextDatePicker = new TextViewDatePicker implement class which shows calendar for user and setup date in text view. I don't know ho to setup this date for this code: Calendar dateOfYourBirth = new GregorianCalendar();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_fragment);
editTextForAge = (TextView) findViewById(R.id.ed_calendar);
Window window = this.getWindow();
TextViewDatePicker editTextDatePicker = new TextViewDatePicker(ProfileGeneral.this, editTextForAge);
Calendar dateOfYourBirth = new GregorianCalendar();
Calendar today = Calendar.getInstance();
int yourAge = today.get(Calendar.YEAR) - dateOfYourBirth.get(Calendar.YEAR);
dateOfYourBirth.add(Calendar.YEAR, yourAge);
if (today.before(dateOfYourBirth)) {
yourAge--;
}
And this is class which showing calendar for user:
public class TextViewDatePicker
implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
public static final String DATE_SERVER_PATTERN = "yyyy-MM-dd";
private DatePickerDialog mDatePickerDialog;
private TextView mView;
private Context mContext;
private long mMinDate;
private long mMaxDate;
public TextViewDatePicker(Context context, TextView view) {
this(context, view, 0, 0);
}
public TextViewDatePicker(Context context, TextView view, long minDate, long maxDate) {
mView = view;
mView.setOnClickListener(this);
mView.setFocusable(false);
mContext = context;
mMinDate = minDate;
mMaxDate = maxDate;
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
Date date = calendar.getTime();
SimpleDateFormat formatter = new SimpleDateFormat(DATE_SERVER_PATTERN);
mView.setText(formatter.format(date));
}
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
mDatePickerDialog = new DatePickerDialog(mContext, this, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
if (mMinDate != 0) {
mDatePickerDialog.getDatePicker().setMinDate(mMinDate);
}
if (mMaxDate != 0) {
mDatePickerDialog.getDatePicker().setMaxDate(mMaxDate);
}
mDatePickerDialog.show();
}

This goes a lot easier with java.time, the modern Java date and time API.
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// date picker month is 0-based, so add 1 to it
LocalDate datePickerDate = LocalDate.of(year, monthOfYear + 1, dayOfMonth);
mView.setText(datePickerDate.toString());
LocalDate today = LocalDate.now(ZoneId.of("America/Tortola"));
long yourAge = ChronoUnit.YEARS.between(datePickerDate, today);
}
Can you use this on Android? Certainly! For most Android devices you will need to get ThreeTenABP, the backport of java.time from Java 8 to Android Java 7. It is all well explained in this question: How to use ThreeTenABP in Android Project (that is ThreeTen for JSR-310, where java.time wsa first described, and ABP for Android Backport).
Please substitute your desired time zone if it doesn’t happen to be America/Tortola.

You used wrong constructor for TextViewDatePicker
Update code :
TextViewDatePicker editTextDatePicker = new TextViewDatePicker(ProfileGeneral.this, editTextForAge);
with
TextViewDatePicker editTextDatePicker = new TextViewDatePicker(ProfileGeneral.this, editTextForAge,0,0);

Related

setting up a Java.time datePicker

I'm switching my app over to Java.time from using the built in Gregorian calendar as I've been told its a better way to go. Is there a way to do a date picker like I've done in the code below with java.time? If not, is there something similar?
private void buildDatePicker(){
final String myFormat = "MMM dd, yyyy"; //sets format in which to show date
final SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());
Date c = calendar.getTime(); //gets the current date
String formattedDate = sdf.format(c); //runs date through formatter
etDate.setText(formattedDate); // sets the etDate edittext to the current date
final DatePickerDialog.OnDateSetListener datePicker = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
etDate.setText(sdf.format(calendar.getTime()));
}
};
etDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(getContext(), datePicker, calendar
.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
Your code is neither complete nor consistent. And I do not do Android, so I am not familiar with the specific framework classes. So I cannot provide a complete example.
But I can show some rough code translated to use java.time.
private void buildDatePicker ( )
{
// Automatically localize the format of the date string.
// Perhaps not make `formatter` object `final` as the user's locale might change during runtime.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.getDefault() );
etDate.setText( myLocalDate.format( formatter ) ); // sets the etDate edittext to the current date
final DatePickerDialog.OnDateSetListener datePicker = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet ( DatePicker view , int year , int monthOfYear , int dayOfMonth )
{
LocalDate localDate = LocalDate.of( year , monthOfYear , dayOfMonth ); // Uses sane numbering for year and month, unlike the `Calendar`/`Date`.
etDate.setText( myLocalDate.format( formatter ) );
}
};
etDate.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick ( View v )
{
// TODO Auto-generated method stub
new DatePickerDialog( getContext() , datePicker , myLocalDate.getYear() , myLocalDate.getMonthValue() , myLocalDate.getDayOfMonth() )
.show();
}
} );
}
Much simpler with java.time than with the terrible legacy classes Calendar, Date, SimpleDateFormat, and such.
This has been covered many times already on Stack Overflow. Search to learn more.

Open DatePicker with suggested date

I need to open a DatePicker with a default date based on the YEAR-MONTH-DAY_OF_MONTH properties of a GregorianCalendar.
Here is the code where I open the DatePicker:
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
For exemple, if my values are like this:
MyCalendar.YEAR = 2017
MyCalendar.MONTH = 2
MyCalendar.DAY_OF_MONTH = 22
The default value set when I open the DatePicker would be:
What do I have to add to do that?
Basically straight from Android | Pickers
Plus, just like any other Fragment, you can use set and get-Arguments to pass data into the fragment.
Details: Best practice for instantiating a new Android Fragment
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public static DatePickerFragment newInstance(int year,int month,int day) {
Bundle b = new Bundle();
b.putInt("year", year);
// put others...
Fragment f = new DatePickerFragment();
f.setArguments(b);
return f;
}
#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);
// Update using the arguments
Bundle args = getArguments();
if (args != null) {
year = args.getInt("year");
// get others...
}
// 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
}
}
And use that newInstance method.
DialogFragment newFragment = DatePickerFragment.newInstance(2017,02,07);
newFragment.show(getFragmentManager(), "datePicker");

Setting user picked date from DatePicker to Calendar

So I need for user to select date from DatePicker Dialog and then when he selects date I want it to be shown on Calendar. For example, if user selects 01/01/2016 I want that date to be shown as some red marked date.
Here's my code:
displayDatumaDodajPisaniIspit = (TextView)dialog. findViewById(R.id.displayDatumaDodajPisaniIspit);
set = (Button)dialog. findViewById(R.id.set);
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(HomeScreen.this, listener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
And the listener
DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
displayDatumaDodajPisaniIspit.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
calendarView.setDateSelected();
}
};
I don't have idea how to start with it. Tried with some methods in listener but it didn't work.
You should first convert the chosen date into millis -
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
long millis = calendar.getTimeInMillis();
and then set the date in your CalendarView like this -
calendarView.setDate(millis);
As you mentioned you are using MaterialCalendarView, then I guess you can use -
calendarView.setSelectedDate(CalendarDay.from(year,monthOfYear,dayOfMonth));

How to convert datepicker format to dd-MM-yyyy

In my database table I use a date format which inserts dates like 04-04-2015.
Then using a datePicker through variable from_date I choose the same date and that date is like 4-4-2015. If I want to select rows using the date selected
from datepicker I get no rows even though rows are available. How can I change the
datePicker date to 04-04-2015 from 4-4-2015, or insert the date like
4-4-2015 instead of 04-04-2015?
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
dateView.setText(new StringBuilder()
// Month is 0 based so add 1
.append(day).append("-") //day
.append(month+1).append("-")//month
.append(year).append(" "));//year
from_date=dateView.getText().toString();
startActivity(new Intent(datefrom.this, dateto.class));
}
};
Code for insertion:
contentvalues.put(VivzHelper.TX_DATE, new SimpleDateFormat("dd-MM-yyyy").format(new Date()));
Using String.format you can achieve what you need.
int day=5,month=4,year=2015;
String date=String.format("%02d-%02d-%d ", day,month,year);
//output date =05-04-2015
private String getDateTime(int year, int month, int day){
Calendar cal = Calendar.getInstance();
cal.set(year, month, day);
String format = "dd-MM-yyyy";
return new SimpleDateFormat(format).format(cal.getTime());
}
You can achieve this using SimpleDateFormat class. For more information visit http://developer.android.com/reference/java/text/SimpleDateFormat.html.
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
Calendar myCalendar = Calendar.getInstance();
myCalendar.set(year, month, day);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
String dateString = formatter.format(myCalendar.getTime());
dateView.setText(dateString);
from_date=dateString;
startActivity(new Intent(datefrom.this, dateto.class));
}
};

DateFormat produces incorrect output

I've got a couple of Buttons that initially display the current date and the current time, respectively. When clicking in the Button that displays the date, it shows a DatePickerFragment that allows the user to choose a date, and then changes the Button's text to the date selected by the user. The other Button does exactly the same but with a TimePickerFragment.
To initialize the Buttons I use the following code:
protected void onCreate(Bundle savedInstanceState){
...
df = DateFormat.getDateInstance();
tf = DateFormat.getTimeInstance();
initDate = new GregorianCalendar();
...
updateDateButtons();
updateTimeButtons();
}
private void updateTimeButtons() {
tf.setCalendar(initDate);
String text = tf.format(initDate.getTime());
btnIniTime.setText(text.substring(0, text.lastIndexOf(":")));
}
private void updateDateButtons() {
df.setCalendar(initDate);
btnIniDate.setText(df.format(initDate.getTime()));
}
Initially, both buttons behave in an expected manner: btnIniTime shows the current time, and btnIniDate shows the current date.
As I said, when the user clicks the btnIniTime button, it shows a TimePickerFragment that prompts the user to choose a time, and the selected time is correctly displayed in btnIniTime.
The problem starts with btnIniDate, that should do the same, but using a DatePickerFragment instead of a TimePickerFragment. When the user selects a date, the button then displays an incorrect date. For example, if I choose 2013 Aug 30, the displayed date turns to be 2013 Aug. 26. If I choose 2013 Sep 1, it then shows 2013 Sep 29!
The classes and methods that I use to change the date ara arranged in the following way:
public abstract static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
protected TaskActivity activity;
protected Calendar c;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (TaskActivity) activity;
}
#Override
public abstract Dialog onCreateDialog(Bundle savedInstanceState);
public void onDateSet(DatePicker view, int year, int month, int day) {
if(activity instanceof TaskActivity){
setDateResult(year, month, day);
}
}
protected abstract void setDateResult(int year, int month, int day);
}
public static class InitDatePickerFragment extends DatePickerFragment {
#Override
protected void setDateResult(int year, int month, int day) {
activity.setInitDate(year, month, day);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = activity.getInitDate();
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 Calendar getInitDate() {
return initDate;
}
public void setInitDate(int year, int month, int day){
Log.d("TaskActivity", "Year: " + year + "; Month: " + month + "; Day: " + day);
initDate.set(Calendar.YEAR, year);
initDate.set(Calendar.MONTH, month);
initDate.set(Calendar.DAY_OF_WEEK, day);
updateDateButtons();
}
When you push the button:
#Override
public void onClick(View v) {
if(v.equals(btnIniDate)){
DialogFragment newFragment = new InitDatePickerFragment();
newFragment.show(getSupportFragmentManager(), "initDatePicker");
}
...
}
By the way, when setting the date, LogCat produces the following output (I've chosen 2013 Aug 30):
Year: 2013; Month: 7; Day:30
The Problem might be
initDate.set(Calendar.DAY_OF_WEEK, day);
in your setInitDate(). This updates only the day of the week. So your date jumps +-6
use
initDate.set(Calendar.DAY_OF_MONTH, day);

Categories

Resources