开发者

Creating Java object with boost::posix_time::ptime serialized XML representation

开发者 https://www.devze.com 2022-12-17 07:26 出处:网络
I have following XML generated by serializing a boost::posix_time::ptime structure. I want to create a Java Date object with this XML.

I have following XML generated by serializing a boost::posix_time::ptime structure. I want to create a Java Date object with this XML.

<timeStamp class_id="0" tracking_level="0" version="0">
    <ptime_date class_id="1" tracking_level="0" version="0">
        <date>20100119</date>
    </ptime_date>
    <ptime_time_duration class_id="2" tracking_level="0" version="0">
        <time_duration_hours>11</time_duration_hours>
        <time_duration_minutes>53</time_duration_minutes>
        <time_duration_seconds>33</time_duratio开发者_运维问答n_seconds>
        <time_duration_fractional_seconds>0</time_duration_fractional_seconds>
    </ptime_time_duration>
</timeStamp>

Below is the Java code that is supposed to construct Date object by de-serializing this XML. Problem that I am facing is how to break the <date> tag into year/month/day sequence.

Integer date = timeStamp.getPtimeDate().getDate();
Integer hrs = timeStamp.getPtimeTimeDuration().getTimeDurationHours();
Integer mins = timeStamp.getPtimeTimeDuration().getTimeDurationMinutes();
Integer secs = timeStamp.getPtimeTimeDuration().getTimeDurationSeconds();

Calendar cal = Calendar.getInstance();
//TODO
//cal.set(year, month, day, hrs, mins, secs);
Date date = cal.getTime();

Any hints?

EDIT:

I am looking for some elegant solution that doesn't require converting date to a string and then splitting it. That would be my last resort.

Thanks


As you don't want to use a String (though I urge you to reconsider, after all that's what it is and easier to parse too), I guess you can do regular old division to extract parts. i.e.

int tmp = date; // unboxing
int year = tmp / 10000;
int month = (tmp % 10000) / 100;
int day = tmp % 100;

That's not very elegant either.

The best way to handle this would be to instruct whatever you're using to deserialize to give you back a String for date instead of an Integer. Then you can just take the first four characters for your, next two for month and last two for day. SimpleDateFormat can do the heavy lifting here.

0

精彩评论

暂无评论...
验证码 换一张
取 消