Avro Java API Timestamp Logical Type?

Thanks to DontPanic:

    Schema timestampMilliType = LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG));

    Schema schemaWithTimestamp = SchemaBuilder
            .record("MyRecord").namespace("org.demo")
            .fields()
            .name("timestamp_with_logical_type").type(timestampMilliType).noDefault()
            .name("timestamp_no_logical_type").type().longType().noDefault()
            .endRecord();

    System.out.println(schemaWithTimestamp.toString(true));

This results in:

{
  "type" : "record",
  "name" : "MyRecord",
  "namespace" : "org.demo",
  "fields" : [ {
    "name" : "timestamp_with_logical_type",
    "type" : {
      "type" : "long",
      "logicalType" : "timestamp-millis"
    }
  }, {
    "name" : "timestamp_no_logical_type",
    "type" : "long"
  } ]
}

Thanks for the first solution, now for nullable logicalType like:

{ 
"name":"maturityDate",
  "type":["null", {
    "type":"long","logicalType":"timestamp-millis"
    }]
},

I figure the following:

        Schema timestampMilliType = LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG));

        Schema clientIdentifier = SchemaBuilder.record("ClientIdentifier")
                .namespace("com.baeldung.avro")
                .fields()
                .requiredString("hostName")
                .requiredString("ipAddress")
                .name("maturityDate")
                .type()
                .unionOf()
                .nullType()
                .and()
                .type(timestampMilliType)
                .endUnion()
                .noDefault()
                .endRecord();

Tags:

Time

Java

Avro