在 Java 中,可以使用 SimpleDateFormat 类来进行时间字符串的格式识别和转换。\n\n下面是一个示例代码,演示如何使用 SimpleDateFormat 来自动识别时间字符串的格式:\n\njava\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\npublic class TimeFormatRecognition {\n public static void main(String[] args) {\n String[] timeStrings = {"2021-01-01", "2021-01-01 12:00:00", "2021-01-01 12:00:00.123"};\n\n for (String timeString : timeStrings) {\n String format = detectTimeFormat(timeString);\n System.out.println("Time string: " + timeString + ", Format: " + format);\n }\n }\n\n public static String detectTimeFormat(String timeString) {\n String[] formats = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.SSS"};\n\n for (String format : formats) {\n try {\n SimpleDateFormat sdf = new SimpleDateFormat(format);\n sdf.parse(timeString);\n return format;\n } catch (ParseException e) {\n // Format does not match, continue to next format\n }\n }\n\n return null; // Cannot recognize the format\n }\n}\n\n\n上述代码中,detectTimeFormat 方法用于识别时间字符串的格式。它尝试使用预定义的日期格式逐个解析时间字符串,如果解析成功,则返回该格式;如果所有格式都无法解析成功,则返回 null。\n\n在示例代码中,我们定义了三个常见的日期格式,即 "yyyy-MM-dd"、"yyyy-MM-dd HH:mm:ss" 和 "yyyy-MM-dd HH:mm:ss.SSS"。你可以根据实际需求添加或修改这些格式。\n\n运行示例代码,会输出每个时间字符串的识别结果,例如:\n\n\nTime string: 2021-01-01, Format: yyyy-MM-dd\nTime string: 2021-01-01 12:00:00, Format: yyyy-MM-dd HH:mm:ss\nTime string: 2021-01-01 12:00:00.123, Format: yyyy-MM-dd HH:mm:ss.SSS\n\n\n通过这种方式,你可以自动识别时间字符串的格式,并根据需要进行后续操作。

Java 自动识别时间字符串格式:示例代码和解析

原文地址: https://www.cveoy.top/t/topic/qhRs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录