Skip to content

Commit

Permalink
time format parse
Browse files Browse the repository at this point in the history
  • Loading branch information
Kuangcp committed Aug 22, 2024
1 parent c7301b1 commit 78553ae
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 9 deletions.
33 changes: 24 additions & 9 deletions class/src/test/java/time/LocalDateTest.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,37 @@
package time;

import java.time.LocalDate;
import java.time.LocalDateTime;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

/**
* @author kuangcp on 18-9-12-下午7:05
*/
@Slf4j
public class LocalDateTest {

@Test
public void testFromLocalDateTime() {
LocalDate localDate = LocalDateTime.now().toLocalDate();
LocalDate last = LocalDateTime.now().plusDays(-1).toLocalDate();
@Test
public void testFromLocalDateTime() {
LocalDate localDate = LocalDateTime.now().toLocalDate();
LocalDate last = LocalDateTime.now().plusDays(-1).toLocalDate();

log.info("{}", localDate);
log.info("{}", last);
}

@Test
public void testFormatParse() throws Exception {
// 注意接口使用差异
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMdd");
TemporalAccessor ta = format.parse("20230804");
System.out.println(ta);

log.info("{}", localDate);
log.info("{}", last);
}
LocalDate parse = LocalDate.parse("20171018", format);
System.out.println(parse);
System.out.println(format.format(parse));
}
}
12 changes: 12 additions & 0 deletions class/src/test/java/time/LocalDateTimeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;

import static org.hamcrest.Matchers.lessThan;
Expand Down Expand Up @@ -61,6 +63,16 @@ public void testFormat() throws Exception {
LocalDateTime last = LocalDateTime.parse(str, format);
System.out.println(last);
System.out.println(format.format(last));

format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println(format.format(LocalDate.now()));
}

@Test(expected = DateTimeParseException.class)
public void testParseError() throws Exception {
// 字符串内不含时间,解析失败
LocalDateTime yyyyMMdd = LocalDateTime.parse("20230804", DateTimeFormatter.ofPattern("yyyyMMdd"));
System.out.println(yyyyMMdd);
}

}

0 comments on commit 78553ae

Please sign in to comment.