如何获得信用卡到期格式的年份字符串

时间:2017-04-04 05:06:04

标签: android

我的代码如下所示:

expiry.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    formatCardExpiringDate(s);
                } catch (NumberFormatException e) {
                    s.clear();
                    //Toast message here.. Wrong date formate

                }
            }
        });

private void formatCardExpiringDate(Editable s) {
        String input = s.toString();


        SimpleDateFormat formatter = new SimpleDateFormat("MM/yy", Locale.ENGLISH);
        Calendar expiryDateDate = Calendar.getInstance();

        try {
            expiryDateDate.setTime(formatter.parse(input));
        } catch (java.text.ParseException e) {
            if (s.length() == 2 && !mLastInput.endsWith("/") && isSlash) {
                isSlash = false;
                int month = Integer.parseInt(input);
                if (month <= 12) {
                    expiry.setText(expiry.getText().toString().substring(0, 1));
                    expiry.setSelection(expiry.getText().toString().length());
                } else {
                    s.clear();
                    expiry.setText("");
                    expiry.setSelection(expiry.getText().toString().length());
                    Toast.makeText(getActivity(), "Enter a valid month", Toast.LENGTH_LONG).show();
                }
            } else if (s.length() == 2 && !mLastInput.endsWith("/") && !isSlash) {
                isSlash = true;
                int month = Integer.parseInt(input);
                if (month <= 12) {
                    expiry.setText(expiry.getText().toString() + "/");
                    expiry.setSelection(expiry.getText().toString().length());
                } else if (month > 12) {
                    expiry.setText("");
                    expiry.setSelection(expiry.getText().toString().length());
                    s.clear();

                }


            } else if (s.length() == 1) {

                int month = Integer.parseInt(input);
                if (month > 1 && month < 12) {
                    isSlash = true;
                    expiry.setText("0" + expiry.getText().toString() + "/");
                    expiry.setSelection(expiry.getText().toString().length());
                }
            }

            mLastInput = expiry.getText().toString();
            return;
        }
    }

我已经编写了上面的代码,在输入两位数字后自动添加 / 。有些人,我在这里只获得 12 / MM / < / strong>对于最终字符串,那么我怎样才能在 / 之后获得 yy

1 个答案:

答案 0 :(得分:1)

尝试MM / YY

new SimpleDateFormat("MM/YY, Locale.ENGLISH);