zoukankan      html  css  js  c++  java
  • Java 8 – How to format LocalDateTime

    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

    http://www.mkyong.com/java8/java-8-how-to-format-localdatetime/

    http://www.mkyong.com/tutorials/java-date-time-tutorials/

  • 相关阅读:
    JavaScript-4.2函数,变量作用域---ShinePans
    2019-8-31-C#-简单读取文件
    2019-8-31-C#-简单读取文件
    2019-8-31-C#-大端小端转换
    2019-8-31-C#-大端小端转换
    2019-6-11-C#-标准性能测试
    2019-6-11-C#-标准性能测试
    2018-2-13-win10-uwp-右击选择-GridViewItem-
    2018-2-13-win10-uwp-右击选择-GridViewItem-
    2019-8-31-NuGet-如何设置图标
  • 原文地址:https://www.cnblogs.com/shy1766IT/p/10127696.html
Copyright © 2011-2022 走看看