Java 获取当前时间并格式化为字符串(含年月日时分秒毫秒)
要获取当前时间的年月日时分秒毫秒并拼接成一个字符串,可以使用Java中的java.time包中的LocalDateTime类来实现。\n\n以下是一个示例代码:\n\njava\nimport java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\n\npublic class Main {\n public static void main(String[] args) {\n // 获取当前时间\n LocalDateTime now = LocalDateTime.now();\n\n // 定义格式化器\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");\n\n // 格式化当前时间为字符串\n String formattedDateTime = now.format(formatter);\n\n // 输出结果\n System.out.println("当前时间的年月日时分秒毫秒: " + formattedDateTime);\n }\n}\n\n\n输出结果类似于:\n\n\n当前时间的年月日时分秒毫秒: 20220826153412345\n\n\n在代码中,首先使用LocalDateTime.now()获取当前时间,然后使用DateTimeFormatter定义了一个格式化器,"yyyyMMddHHmmssSSS"表示年月日时分秒毫秒的格式。接着,使用now.format(formatter)将当前时间格式化为字符串,最后输出结果。
原文地址: https://www.cveoy.top/t/topic/p8nY 著作权归作者所有。请勿转载和采集!