Java: Date and LocalDateTime get current time

Date gets the current time

// @since   JDK1.0
public class Date{
    
    }

example

package com.example;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        // 获取当前时间
        Date date = new Date();
        System.out.println(date);
        // Sun May 28 17:49:22 CST 2023

        // 格式化
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date));
        // 2023-05-28 17:49:22
    }
}

LocalDateTime gets the current time

// @since 1.8
public final class LocalDateTime{
    
    }

example

package com.example;

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

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        // 获取当前时间
        LocalDateTime date = LocalDateTime.now();

        System.out.println(date);
        // 2023-05-28T17:52:30.585

        // 格式化
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date));
        // 2023-05-28 17:52:30
    }
}

Guess you like

Origin blog.csdn.net/mouday/article/details/130915394