java判断时间格式是否正确的代码怎么写

32次阅读
没有评论

共计 873 个字符,预计需要花费 3 分钟才能阅读完成。

你可以使用 SimpleDateFormat 类来判断时间格式是否正确。下面是一个示例代码:

import java.text.ParseException;
import java.text.SimpleDateFormat;
public class TimeFormatChecker {public static boolean isTimeFormatCorrect(String time, String pattern) {SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setLenient(false); // 设置严格的解析,不容忍任何错误
try {sdf.parse(time);
return true;
} catch (ParseException e) {return false;}
}
public static void main(String[] args) {
String time1 = "09:30";
String time2 = "9:30 AM";
String pattern = "HH:mm";
System.out.println(isTimeFormatCorrect(time1, pattern)); // 输出: true
System.out.println(isTimeFormatCorrect(time2, pattern)); // 输出: false
}
}

在上述代码中,isTimeFormatCorrect() 方法接受两个参数:要检查的时间字符串和时间格式的模式。通过创建 SimpleDateFormat 对象并使用 parse() 方法来尝试解析给定的时间字符串。如果解析成功,则说明时间格式正确;如果解析失败,就捕获 ParseException 异常,并返回 false 表示时间格式不正确。
main() 方法中,我们使用了两个示例时间字符串和一个时间格式模式来测试 isTimeFormatCorrect() 方法。输出应该是 truefalse。你可以根据你自己的需求修改时间字符串和时间格式模式。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-16发表,共计873字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)