美文网首页
Date时间

Date时间

作者: yangyangrenren | 来源:发表于2018-08-13 14:55 被阅读0次

    使用jackson对Date类型数据进行处理时候,会自动转换为距离1970年1月1日的毫秒数,如1534128602500,其实是2018-08-13 10:50:02的时间。

    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.text.SimpleDateFormat;
    ObjectMapper mapper = new ObjectMapper();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
    mapper.setDateFormat(sdf);
    byte[] json = mapper.writeValueAsBytes(schema);
    

    在elasticsearch中,对于Date格式的数据,如果不加上上面的格式转换,并且没有事先对elasticsearch中index mapping字段类型进行定义,那么新的字段将会默认是number类型的。

    Date datatype
    JSON doesn’t have a date datatype, so dates in Elasticsearch can either be:

    • strings containing formatted dates, e.g. "2015-01-01" or "2015/01/01 12:10:30".
    • a long number representing milliseconds-since-the-epoch.
    • an integer representing seconds-since-the-epoch.

    Internally, dates are converted to UTC (if the time-zone is specified) and stored as a long number representing milliseconds-since-the-epoch.

    Queries on dates are internally converted to range queries on this long representation, and the result of aggregations and stored fields is converted back to a string depending on the date format that is associated with the field.

    其他方法,可供参考(未验证):
    1.默认是转成timestamps形式的,通过下面方式可以取消timestamps。

    objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
    
    1. annotaion
      @JsonIgnoreProperties
      @JsonIgnore
      @JsonFormat
      @JsonSerialize
      具体见:https://blog.csdn.net/u013614451/article/details/39699007

    3.参考https://www.baeldung.com/jackson-serialize-dates,这里提供了很多方法函数

    其他参考
    Date format Mapping to JSON Jackson
    ElasticSearch Spring-Data Date format always is long

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    System.out.println(sdf.parse("2015-08-01T06:51:14.000+08:00"));
    Date date = sdf.parse("2015-08-01T06:51:14.000+08:00");
    
    
    //OffsetDateTime offsetDateTime = LocalDateTime.parse("2018-02-14T06:30").atOffset(ZoneOffset.ofHours(2));
    // Uses DateTimeFormatter.ISO_OFFSET_DATE_TIME for which the default format is
    // ISO_LOCAL_DATE_TIME followed by the offset ("+HH:mm:ss").
    OffsetDateTime offsetDateTime = OffsetDateTime.parse("2019-03-04T03:30:53+08:00");
    long dddd = offsetDateTime.getLong(ChronoField.INSTANT_SECONDS);
    
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String formatStr =formatter.format(new Date(dddd*1000));
    System.out.println(formatStr);
    

    相关文章

      网友评论

          本文标题:Date时间

          本文链接:https://www.haomeiwen.com/subject/qpgybftx.html