简体   繁体   中英

How do I check if a string is in this format MM-YY in Java ?

我必须在数据库中添加一个格式为“ MM-YY”的字符串,该字符串表示信用卡的到期日期,其中MM是月份,而YY是年份的最后两位数字,如何检查字符串是否在这是Java的这种特定格式吗?

Use a regular expression:

String myString = "12-99";

if( myString.matches("((0[1-9])|(1[0-2]))-\\d{2}") ){
   System.out.println("Correct format");
}
else{
  System.out.println("Incorrect format");
}

Try Using below regex

String str = "10-18";
if (str.matches("([0-9]{2})-([0-9]{2})"))
 System.out.println("Correct");
else 
System.out.println("Incorrect");

java.time.YearMonth

Parse as a YearMonth . Trap for exception.

String input = "99-18" ;  // Valid: "01-18"  Invalid: "99-18"
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-uu" ) ;

YearMonth ym = null ;
try {
    ym = YearMonth.parse( input , f ) ;
} catch ( DateTimeParseException e ) {
    System.out.println( "Invalid input: " + input ) ;
}

System.out.println( "ym.toString(): " + ym ) ;

See this code run live on IdeOne.com .

Invalid input: 99-18

ym.toString(): null


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM