Harry Potter
Harry Potter

Reputation: 176

How to retrieve value from String?

Here dob is String value . How I will get a particular value from String. Please check my code I mention there were I need it.

public class MainActivity extends AppCompatActivity {
        private EditText editTextDate;
           private Button mButton;

          private static final String DATE_FORMAT = "dd/MM/YYYY";

           @Override
           protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.activity_main);
                      initView();
                      btnClick();
                  }

          private void initView() {
          editTextDate = findViewById(R.id.date);
                 }

        private void btnClick() {
             mButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
                String dob = editTextDate.getText().toString();
                // dob is is a date like 25/05/1995
                // I want to 1995 value. What will i do??
            }
        });
    }
}

Upvotes: 0

Views: 47

Answers (2)

Lalit Fauzdar
Lalit Fauzdar

Reputation: 6361

Although, you can go for splitting the string using a regex, but here, this is what you need to learn. SimpleDateFormat. This will give you a lot more control especially when you'll use time with it.

  • Java

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
Date yourDate = format.parse("25/05/1995");
Calendar yourCal = new Calendar.getInstance();
yourCal.setTime(yourDate);
Log.d("Tag","Day : "+ yourCal.get(Calendar.DAY_OF_MONTH));
Log.d("Tag","Month: " + yourCal.get(Calendar.MONTH) + 1);
Log.d("Tag","Year: " + yourCal.get(Calendar.YEAR));
  • Kotlin

val format = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val yourDate = format.parse("25/05/1995")
val yourCal: Calendar = Calendar.getInstance()
yourCal.time = yourDate!!
Log.d("Tag", "Day : " + yourCal[Calendar.DAY_OF_MONTH])
Log.d("Tag", "Month: " + yourCal.get(Calendar.MONTH) + 1)
Log.d("Tag", "Year: " + yourCal.get(Calendar.YEAR))

Remember, month starts from 0 for January so you've to +1 in that, And capital 'M' denotes month in java where as small 'm' denotes minutes. There are lots of formats for SimpleDateFormat, you can use any of them.

Upvotes: 1

LaoDa581
LaoDa581

Reputation: 613

Just use the appropriate function. String#split()

String dob = editTextDate.getText().split("/")[2]

Upvotes: 0

Related Questions