java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java时间和字符串转换

java时间和字符串之间相互转换几种方法

作者:tomorrow.hello

这篇文章主要介绍了java时间和字符串之间相互转换的几种方法,还详细解释了DateTimeFormatter的三种解析模式,并比较了yyyy和uuuu在严格模式下的区别,需要的朋友可以参考下

1.当前时间对象转字符串

方法一:Date和SimpleDateFormat实现

使用java.util.Date类和java.text.SimpleDateFormat类

public static void main(String[] args) {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(now);
        System.out.println(currentTime);
    }

方法二:LocalDateTime和DateTimeFormatter

使用java.time.LocalDateTime类和java.time.format.DateTimeFormatter类(Java 8及以上版本)

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String currentTime = now.format(dtf);
        System.out.println(currentTime);
    }

方式三:Calendar

public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        String currentTime = String.format("%04d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second);
        System.out.println(currentTime);
    }

方式四:LocalDate和LocalTime

使用java.time.LocalDate类和java.time.LocalTime类(Java 8及以上版本)

 public static void main(String[] args) {
        LocalDate currentDate = LocalDate.now();
        LocalTime currentTime = LocalTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = currentDate.format(dtf);
        String formattedTime = currentTime.format(dtf);
        System.out.println(formattedDate + " " + formattedTime);
    }

2.时间字符串转时间对象

方式一: SimpleDateFormat

        String dateString = "2024-10-28 22:56:11";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.parse(dateString);

 方式二:DateTimeFormatter

DateTimeFormatter有三种解析模式:

SMART智能模式:

        testTime("2023-02-33 22:56:11");
        testTime("2023-02-30 22:56:11");    


private static void testTime(String dateString){
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        try {
            LocalDateTime localDateTime = LocalDateTime.parse(dateString, sdf);
            System.out.println("转换后时间:" + localDateTime);
        } catch (Exception ex) {
            System.err.println("转换失败:" + ex.getMessage());
        }
    }

LENIENT宽松模式:

        testTime("2023-02-33 22:56:11");
        testTime("2023-02-30 22:56:11");

   
 private static void testTime(String dateString){
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                .withResolverStyle(ResolverStyle.LENIENT);
        try {
            LocalDateTime localDateTime = LocalDateTime.parse(dateString, sdf);
            System.out.println("转换后时间:" + localDateTime);
        } catch (Exception ex) {
            System.err.println("转换失败:" + ex.getMessage());
        }
    }

STRICT严格模式:

严格模式下时间字符串的年份格式化分为yyyy和uuuu两种。当DateTimeFormatter.ofPattern()进行非严格模式下的格式化的时候,yyyy/MM/dd和uuuu/MM/dd表现相同,都是转换为合法的日期。

yyyy:

yyyy代表公元纪年,在严格模式下,如果时间字符串不包含公元,因此程序报错。

        testTime("2023-02-20 22:56:11");
        testTime("2023-02-30 22:56:11");
   
 private static void testTime(String dateString){
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                .withResolverStyle(ResolverStyle.STRICT);
        try {
            LocalDateTime localDateTime = LocalDateTime.parse(dateString, sdf);
            System.out.println("转换后时间:" + localDateTime);
        } catch (Exception ex) {
            System.err.println("转换失败:" + ex.getMessage());
        }
    }

使用G yyyy/MM/dd来进行格式化 ,并且在时间字符串中也增加了公元单位。

        testTime("公元 2023-02-20 22:56:11");
        testTime("公元 2023-02-30 22:56:11");

private static void testTime(String dateString){
        /**
         *  Locale.JAPAN  --> "西暦 yyyy-MM-dd"
         *  Locale.CHINA  --> "公元 yyyy-MM-dd"
         *  Locale.US     --> "AD yyyy-MM-dd"
         */
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("G yyyy-MM-dd HH:mm:ss",Locale.CHINESE)
                .withResolverStyle(ResolverStyle.STRICT);
        try {
            LocalDateTime localDateTime = LocalDateTime.parse(dateString, sdf);
            System.out.println("转换后时间:" + localDateTime);
        } catch (Exception ex) {
            System.err.println("转换失败:" + ex.getMessage());
        }
    }

uuuu: 

uuuu不代表公元格式化,所以不会存在异常。

        testTime("2023-02-20 22:56:11");
        testTime("2023-02-29 22:56:11");

  
private static void testTime(String dateString){
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss")
                .withResolverStyle(ResolverStyle.STRICT);
        try {
            LocalDateTime localDateTime = LocalDateTime.parse(dateString, sdf);
            System.out.println("转换后时间:" + localDateTime);
        } catch (Exception ex) {
            System.err.println("转换失败:" + ex);
        }
    }

总结 

到此这篇关于java时间和字符串之间相互转换几种方法的文章就介绍到这了,更多相关java时间和字符串转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文