2
votes

I am trying to translate a message generated using C# to JAVA. As a first step, i generated proto file and this is what i got

package Om.Business.Scanner;

message ScannerActivityDetail {
   optional string ActivityId = 1;
   optional string ContextId = 2;
   optional int32 ActivityStart = 3;
   optional bcl.DateTime ActivityEnd = 4;
}

How do i interpret bcl.DateTime in java world?

I am using protobuf-net and trying to de-serialize message generated by C# app.

Thanks in advance for your help.

1
If you are using cross-platform, I would suggest handling date/times more simply as a long of some interval into an epoch (traditionally 1 jan 1970) - Marc Gravell

1 Answers

3
votes

Looking at bcl.proto, it should be pretty straightforward. Create a Map<DateTime.TimeSpanScale, TimeUnit> in the obvious way, then:

public static Date toDate(bcl.DateTime proto) {
    TimeUnit unit = SCALE_TO_UNIT_MAP.get(proto.getScale());
    if (unit == null) {
        throw new IllegalArgumentException("Invalid scale: " + proto.getScale());
    }
    long millis = unit.toMillis(proto.getValue());
    return new Date(millis);
}

You could use Joda Time's DateTime type in exactly the same way, as it has a constructor accepting a long too. (You might want to think about which time zone to specify though...)