java 8 String 和 LocalDateTime 的转换


String 转换为 LocalDateTime


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Code {
    public static void main(String[] args) {
	// String 转换为 LocalDateTime
        String dateStr = "2021-09-03 21:00:00";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parsedDate = LocalDateTime.parse(dateStr, formatter);
        System.out.println("-----------");

	// String 转换为 LocalDate
        String dateStr2 = "2021-09-03";
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate parsedDate2 = LocalDate.parse(dateStr2, formatter2);
        System.out.println("-----------");
    }
}

LocalDateTime 转换为 String

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM