开发者

Parse JSON date format to String using GSON on Android

开发者 https://www.devze.com 2023-03-13 03:01 出处:网络
I´m getting a lot of dates from a JSON feed. They look like this: \\/Date(1307972400000+0200)\\/ I need to parse these dates into hours and minutes using Java.

I´m getting a lot of dates from a JSON feed.

They look like this: \/Date(1307972400000+0200)\/

I need to parse these dates into hours and minutes using Java.

EDIT:

This is how far I´ve come:

String s = dateString.replaceAll("^/Date\\(" , "");

This gives me the following output: 1307972400000+0200)/

How can I strip the rest of this string, any sugges开发者_JS百科tions?

I want it to like this: 1307972400000L


It is JSON feed from .Net service. I'm using this code:

public class GsonHelper {
    public static Gson createWcfGson() {
        GsonBuilder gsonb = new GsonBuilder();
        gsonb.registerTypeAdapter(Date.class, new WcfDateDeserializer());
        Gson gson = gsonb.create();
        return gson;
    }

    private static class WcfDateDeserializer implements JsonDeserializer<Date>, JsonSerializer<Date> {

        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            String JSONDateToMilliseconds = "\\/(Date\\((.*?)(\\+.*)?\\))\\/";
            Pattern pattern = Pattern.compile(JSONDateToMilliseconds);
            Matcher matcher = pattern.matcher(json.getAsJsonPrimitive().getAsString());
            String result = matcher.replaceAll("$2");
            return new Date(new Long(result));
    }

        @Override
        public JsonElement serialize(Date date, Type arg1, JsonSerializationContext arg2) {
            return new JsonPrimitive("/Date(" + date.getTime() + ")/");
        }
    }
}

It registers custom serializer and deserializer for Date type. Using is simple: Gson gson = GsonHelper.createWcfGson(); and do what you want.

Upd: Sorry, previous example doesn't work with timezones. It's easier to use Calendar to take into account timezone offset. Code will look like this:

public class GsonHelper {
    public static Gson createWcfGson() {
        GsonBuilder gsonb = new GsonBuilder();
        gsonb.registerTypeAdapter(Date.class, new WcfCalendarDeserializer ());
        Gson gson = gsonb.create();
        return gson;
    }

    public static class WcfCalendarDeserializer implements JsonDeserializer<Calendar>, JsonSerializer<Calendar> {

        public Calendar deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

            String JSONDateToMilliseconds = "\\/(Date\\((.*?)(\\+.*)?\\))\\/";
            Pattern pattern = Pattern.compile(JSONDateToMilliseconds);
            Matcher matcher = pattern.matcher(json.getAsJsonPrimitive().getAsString());
            matcher.matches();
            String tzone = matcher.group(3);
            String result = matcher.replaceAll("$2");

            Calendar calendar = new GregorianCalendar();
            calendar.setTimeZone(TimeZone.getTimeZone("GMT" + tzone));
            calendar.setTimeInMillis(new Long(result));

            return calendar;
        }

        @Override
        public JsonElement serialize(Calendar calendar, Type arg1, JsonSerializationContext arg2) {
            return new JsonPrimitive("/Date(" + calendar.getTimeInMillis() + ")/");
        }
    }
}

Then you can use returned Calendar object to get hours and minutes (and adjust timezone if needed).

calendar.get(Calendar.HOUR_OF_DAY);
calendar.get(Calendar.MINUTE);


To augment accepted answer by @Programmer Bruce you can simply use this:

public static Long getTime(String date) {
    if (Utils.isEmpty(date))
        return -1l;
    String t = date.substring(date.indexOf('(') + 1);
    if (date.contains("+"))
        t = t.substring(0, t.indexOf('+'));
    else if (date.contains("-"))
        t = t.substring(0, t.indexOf('-'));
    else
        t = t.substring(0, t.indexOf(')'));
    return new Long(t);
}


How can I strip the rest of this string, any suggestions?

I want it to like this: 1307972400000L

Strictly speaking, you could just get the substring from the start to the '+' character.

String input = "/Date(1307972400000+0200)/";
String result = input.replaceAll("^/Date\\(" , "");
result = result.substring(0, result.indexOf('+'));
System.out.println(new Long(result));
0

精彩评论

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

关注公众号