转载 

Java 8 – How to format LocalDateTime

分类:    265人阅读    IT小君  2018-07-01 09:41

Few examples to show you how to format java.time.LocalDateTime in Java 8.

1. LocalDateTime + DateTimeFormatter

To format a LocalDateTime object, uses DateTimeFormatter

TestDate1.java

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);
      
    }
}

Output


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

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

2. String -> LocalDateTime

Another example to convert a String to LocalDateTime

TestDate2.java

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));

    }
}

Output


Before : 2016-11-09 10:30

After : 2016-11-09T10:30

After : 2016-11-09 10:30

References

  1. DateTimeFormatter JavaDoc
  2. Java 8 – How to convert String to LocalDate
点击广告,支持我们为你提供更好的服务

响应式咖啡饮品宣传网站模板

canvas炫酷鼠标移动文字粒子特效

css鼠标跟随文字模糊特效

小众时尚单品在线电子商务网站模板

中小型创意设计服务公司网站模板

HTML5 Canvas竖直流动线条背景动画特效

HTML5现代家居装潢公司网站模板

有机水果蔬菜HTML5网站模板

jQuery右端悬浮带返回顶部特效

现代时尚家具公司网站模板

html5 svg夜空中星星流星动画场景特效

网页设计开发公司网站模板

html5 canvas进度条圆环图表统计动画特效

html5 canvas彩色碎片组合球形旋转动画特效

js+css3抽奖转盘旋转点餐代码

响应式时尚单品在线商城网站模板

html5图标下拉搜索框自动匹配代码

css+js实现的颜色渐变数字时钟动画特效

响应式太阳能能源公司网站模板

HTML5数字产品服务公司网站模板

点击广告,支持我们为你提供更好的服务
 工具推荐 更多»
点击广告,支持我们为你提供更好的服务