笔记

类型转换

日期类型转换

date->string

Date now = new Date();
String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now)

string->date

String time;
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);

Instant->string

Instant startTime;
String allotStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date.from(startTime));

string->Instant

String t;
Instant time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(t).toInstant();

常用类型转换

list -> list

List ApparatusIds =
        ids.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());

map->string

import org.apache.htrace.shaded.fasterxml.jackson.databind.ObjectMapper;

    Map contentJson = form.getContent();
    if (MapUtils.isNotEmpty(contentJson)) {
      try {
        String content = new ObjectMapper().writeValueAsString(contentJson);
        SOW.setContent(content);
      } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
      }
    }

string->map

import com.google.gson.Gson;

    Map dto = null;
    try {
      Gson gson = new Gson();
      if (StringUtils.isNotBlank(source.getContent())) {
        dto = gson.fromJson(source.getContent(), new TypeToken>() {}.getType());
      }
    } catch (JsonSyntaxException e) {
      throw new RuntimeException("string 转 map 错误");
    }

你可能感兴趣的:(java)