Java 日期时间方法

使用SimpleDateFormate类将时间戳转日期字符串

SimpleDateFormate类的构造函数

SimpleDateFormat() 
SimpleDateFormat(String pattern) 
SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols) 
SimpleDateFormat(String pattern, Locale locale)

其中parttern参数表示的是时间格式如 年月日 时分秒 yyyy-MM-dd HH:mm:ss,精确到毫秒是 yyyy-MM-dd HH:mm:ss.SSS 。

这里用到format方法

public final String format(Date date)

使用SimpleDateFormate类时间戳转日期的例子

package com.yxjc;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test  {

    public static void main(String args[]) throws InterruptedException {
        long timestamp = new Long("1672843199000");//这里需要传入13位时间戳格式
        Date date = new Date(timestamp);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String result = simpleDateFormat.format(date);

        System.out.println(result);
    }

} 

测试一下

输出

2023-01-04 22:39:59

在上面的例子中可以根据需要更改自己的日期格式 parttern。

可以通过  System.currentTimeMillis() 获取当前时间的字符串格式。

long timestamp = System.currentTimeMillis(); 
Date date = new Date(timestamp);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String result = simpleDateFormat.format(date);

System.out.println(result);