【问题标题】:How to retrieve value from String?如何从字符串中检索值?
【发布时间】:2020-05-08 15:13:30
【问题描述】:

这里 dob 是字符串值。我将如何从 String 中获取特定值。请检查我提到的代码是否需要它。

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??
            }
        });
    }
}

【问题讨论】:

    标签: java android string


    【解决方案1】:

    虽然,您可以使用正则表达式拆分字符串,但在这里,这是您需要学习的内容。简单日期格式。这会给你更多的控制权,尤其是当你花时间的时候。

    • 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));
    
    • 科特林

    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))
    

    请记住,月份从一月份的 0 开始,因此您必须在其中 +1,并且大写的“M”在 Java 中表示月份,而小写的“m”表示分钟。 SimpleDateFormat 有多种格式,您可以使用其中的任何一种。

    【讨论】:

    • 非常感谢您,先生
    【解决方案2】:

    只需使用适当的功能。 String#split()

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多