笔记

头像
Sugar
    阅读 2 分钟

    类型转换

    日期类型转换

    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<string> -> list<long>

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

    map->string

    import org.apache.htrace.shaded.fasterxml.jackson.databind.ObjectMapper;
    
        Map<String, Object> 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<String, Object> dto = null;
        try {
          Gson gson = new Gson();
          if (StringUtils.isNotBlank(source.getContent())) {
            dto = gson.fromJson(source.getContent(), new TypeToken<Map<String, Object>>() {}.getType());
          }
        } catch (JsonSyntaxException e) {
          throw new RuntimeException("string 转 map 错误");
        }

    Sugar
    11 声望0 粉丝