문제

I'm trying to get XStream to be able to convert a string that contains a datetime (such as 2013-01-23 16:50:39.495855) into a java.lang.Long instance.

Currently, I have XML like so:

<widget>
    <timestamp val="2013-01-23 16:50:39.495855"/>
</widget>

I want to convert this into a standard Unix epoch timestamp (number of millis since Jan 1, 1970). Since the above datetime translates into a Unix epoch timestamp of (if my math is right) 1358959839000, I'd like XStream to convert this into a new Long(1358959839000) instance.

I don't believe this is possible with XStream's alias methods, and I would probably need to write my own Converter, however a com.thoughtworks.xstream.converters.basic.LongConverter already exists, so I'm not sure how to write my own UnixEpochLongConverter seeing that both converters are attempting to convert a String to a Long. Any ideas? Thanks in advance!

도움이 되었습니까?

해결책

Either register your Custom converter as local using registerLocalConverter or with priority above XStream.PRIORITY_NORMAL.

xstream.registerLocalConverter(
    Widget.class, 
    "timestamp", 
     new UnixEpochLongConverter());

다른 팁

You could use the DateFormat object to convert the string to a java.util.Date object and then do date.getTime() to return a long value . Below is an example. You could write a method in your object that basically converts the string to long.

 String date = "2013-01-23 16:50:39.495855";
 DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
 Date datem = format.parse(date);
 long longDate = datem.getTime();
 System.out.println(longDate);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top