Skip to content

Commit

Permalink
add RFC3339 DateTimeFormatter
Browse files Browse the repository at this point in the history
  • Loading branch information
jiangtj committed Apr 3, 2024
1 parent ed2bdb9 commit 854a970
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
package com.jiangtj.platform.common;

import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;

public interface DatetimeFormatters {
DateTimeFormatter DateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter Date = DateTimeFormatter.ofPattern("yyyy-MM-dd");
DateTimeFormatter Time = DateTimeFormatter.ofPattern("HH:mm:ss");
// RFC3339 for wechat pay v3
DateTimeFormatter RFC3339 = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(Date)
.appendLiteral("T")
.append(Time)
.parseLenient()
.appendOffsetId()
.parseStrict()
.toFormatter();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.jiangtj.platform.common;

import org.junit.jupiter.api.Test;

import java.time.*;

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

class DatetimeFormattersTest {

@Test
public void testFormatters() {
LocalDate date = LocalDate.of(2024, 2, 3);
LocalTime time = LocalTime.of(8, 30, 40);
LocalDateTime datetime = LocalDateTime.of(date, time);
ZonedDateTime zonedDatetime = ZonedDateTime.of(datetime, ZoneId.of("Asia/Shanghai"));

assertEquals("2024-02-03", date.format(DatetimeFormatters.Date));
assertEquals("2024-02-03", datetime.format(DatetimeFormatters.Date));
assertEquals("2024-02-03", zonedDatetime.format(DatetimeFormatters.Date));
assertEquals("08:30:40", time.format(DatetimeFormatters.Time));
assertEquals("08:30:40", datetime.format(DatetimeFormatters.Time));
assertEquals("08:30:40", zonedDatetime.format(DatetimeFormatters.Time));
assertEquals("2024-02-03 08:30:40", datetime.format(DatetimeFormatters.DateTime));
assertEquals("2024-02-03 08:30:40", zonedDatetime.format(DatetimeFormatters.DateTime));
assertEquals("2024-02-03T08:30:40+08:00", zonedDatetime.format(DatetimeFormatters.RFC3339));
}

}

0 comments on commit 854a970

Please sign in to comment.