关于java:笔记

4次阅读

共计 1151 个字符,预计需要花费 3 分钟才能阅读完成。

类型转换

日期类型转换

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 谬误");
    }
正文完
 0