Skip to content

Commit

Permalink
improved SimpleDateFormat compatible, for issue #2206
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Jan 27, 2024
1 parent e3cd07f commit d638047
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public abstract class DateTimeCodec {
protected final boolean yyyyMMddhhmmss14;
protected final boolean yyyyMMdd10;
protected final boolean yyyyMMdd8;
protected final boolean useSimpleDateFormat;

DateTimeFormatter dateFormatter;

Expand All @@ -39,6 +40,7 @@ public DateTimeCodec(String format, Locale locale) {
this.yyyyMMddhhmm16 = "yyyy-MM-dd HH:mm".equals(format);
this.yyyyMMdd10 = "yyyy-MM-dd".equals(format);
this.yyyyMMdd8 = "yyyyMMdd".equals(format);
this.useSimpleDateFormat = "yyyy-MM-dd'T'HH:mm:ssXXX".equals(format);

boolean formatUnixTime = false, formatISO8601 = false, formatMillis = false, hasDay = false, hasHour = false;
if (format != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
import com.alibaba.fastjson2.codec.DateTimeCodec;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;

final class ObjectWriterImplLocalDateTime
Expand Down Expand Up @@ -118,7 +121,14 @@ public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type f
return;
}

String str = formatter.format(ldt);
String str;
if (useSimpleDateFormat) {
Instant instant = ldt.toInstant(jsonWriter.context.getZoneId().getRules().getOffset(ldt));
Date date = new Date(instant.toEpochMilli());
str = new SimpleDateFormat(this.format).format(date);
} else {
str = formatter.format(ldt);
}
jsonWriter.writeString(str);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.alibaba.fastjson2.issues_2200;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.junit.jupiter.api.Test;

import java.time.LocalDateTime;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class Issue2206 {
@Test
public void test() {
Bean bean = new Bean();
bean.birthday = LocalDateTime.of(2012, 2, 3, 12, 13, 14);
String json = JSON.toJSONString(bean);
assertEquals("{\"birthday\":\"2012-02-03T12:13:14+08:00\"}", json);
}

public static class Bean {
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssXXX", timezone = "GMT+8")
public LocalDateTime birthday;
}
}

0 comments on commit d638047

Please sign in to comment.