java 将时间搓转换为 yyyy-MM-dd HH:mm:ss 时间格式字符串

有很多模块 我们可能为了数据精准性 存入数据库了

很多时候 我们数据层拿到 可以选择直接扔给前端 但是 也可以选择 我们这边直接给它转换好格式
首先 我们类中要导入两个包

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

然后 写一个这样的方法

public String TimestampToDateFormat(long timestamp){
    
    
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置日期
   String formattedDate = sdf.format(new Date(timestamp)); // 将时间戳转换为指定格式的日期字符串
   return formattedDate;
}

这就是 将时间搓 转为时间格式字符串 的代码
这里 我们方法接受一个long类型参数 就是要转换的时间搓 然后 转好之后 return 回去一个处理好格式的字符串

我们这里有一个时间搓
在这里插入图片描述
我们直接在测试类中这样写

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest
public class WebDomApplicationTests {
    
    

    @Test
    void set() {
    
    
        Long longNumber = Long.parseLong("1704672412180");
        System.out.println("时间搓: " + TimestampToDateFormat(longNumber));
    }
    public String TimestampToDateFormat(long timestamp){
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置日期
        String formattedDate = sdf.format(new Date(timestamp)); // 将时间戳转换为指定格式的日期字符串
        return formattedDate;
    }
}

这里 我们通过 Long.parseLong将字符串转为狼类型 然后传入我们写的 TimestampToDateFormat中输出结果

运行结果如下
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45966674/article/details/135448361