将Long转换为String
时间: 2024-02-09 17:08:12 浏览: 28
你可以使用Java中的toString()方法将Long类型的数据转换为String类型,示例代码如下:
```java
Long l = 123456789L;
String s = l.toString();
```
或者你也可以使用String类的valueOf()静态方法,示例代码如下:
```java
Long l = 123456789L;
String s = String.valueOf(l);
```
两种方式都可以将Long类型的数据转换为String类型,你可以根据自己的需求选择使用哪种方式。
相关问题
springboot 返回前端数据,利用jackson全局配置将long转换为string,防止精度丢失的代码
可以在SpringBoot项目中的配置类中添加以下代码,实现将Long类型转换为String类型,并避免精度丢失的问题。
```java
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Long.class, ToStringSerializer.instance);
module.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(module);
return objectMapper;
}
}
```
以上代码通过注册自定义的Jackson模块,将Long类型序列化为String类型。这样在SpringBoot项目中返回JSON数据时,Long类型的数据将会默认转换为String类型,避免了精度丢失的问题。
long类型转换为string日期
long类型通常表示的是从1970年1月1日0点0分0秒(即UNIX时间戳)到某个时间的毫秒数。因此,将long类型转换为string日期需要先将其转换为Date类型,然后再将Date类型转换为string日期。
以下是将long类型转换为string日期的Java代码示例:
```java
long milliSeconds = 1612276800000L; // 假设这个long类型表示2021年2月3日0点0分0秒的毫秒数
Date date = new Date(milliSeconds);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(date);
System.out.println(dateString); // 输出:2021-02-03 00:00:00
```
这里使用了SimpleDateFormat类来将Date类型转换为指定格式的string日期。你可以根据自己的需求来指定转换后的日期格式。