java8 LocalDateTime 格式化日期
原创 xingfu2017 发表于:2017-09-18 10:31:52
  阅读 :769   收藏   编辑

2个例子,告诉你如何在Java8中格式化java.time.LocalDateTime

1.日期转字符串

package com.mkyong.time;

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

public class TestDate1 {
    public static void main(String[] args) {

        //Get current date time
        LocalDateTime now = LocalDateTime.now();

        System.out.println("Before : " + now);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        String formatDateTime = now.format(formatter);

        System.out.println("After : " + formatDateTime);

    }
}

输出:

Before : 2016-11-09T11:44:44.797

After  : 2016-11-09 11:44:44

2.字符串转日期

package com.mkyong.time;

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

public class TestDate2 {
    public static void main(String[] args) {

        String now = "2016-11-09 10:30";

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        LocalDateTime formatDateTime = LocalDateTime.parse(now, formatter);

        System.out.println("Before : " + now);

        System.out.println("After : " + formatDateTime);

        System.out.println("After : " + formatDateTime.format(formatter));

    }
}

输出:

Before : 2016-11-09 10:30

After : 2016-11-09T10:30

After : 2016-11-09 10:30

参考:java-8-how-to-format-localdatetime