Generate past date as string format YYYYMMDD 生成过去的日期,格式为YYYYMMDD

huangapple go评论57阅读模式
英文:

Instancio - Generate past date as string format YYYYMMDD

问题

我试图使用Instancio来生成测试数据。Student类有一个名为birthdate的成员,类型为String,用于以YYYYMMDD的格式存储日期。

我该如何使用Instancio库(测试数据生成器)生成一个格式为yyyyMMdd的日期作为字符串?

这是我的起点:

Student student = Instancio.of(Student.class)
  .generate(field(Student::getBirthdate), gen -> gen.temporal().localDate().past())
  .create();

谢谢

英文:

I'm trying to use Instancio to generate data for testing. The Student class has a birthdate member as a String type to store the date in the format YYYYMMDD.

How can I use Instancio library (test data generator) to generate a date in the format yyyyMMdd as string?

Here was my starting poing:

Student student = Instancio.of(Student.class)
  .generate(field(Student::getBirthdate), gen -> gen.temporal().localDate().past())
  .create();

Thx

答案1

得分: 1

如评论中建议的,最好将字段声明为LocalDate而不是String。如果您不能更改它,可以使用as()方法将日期映射到字符串:

Student student = Instancio.of(Student.class)
  .generate(field(Student::getBirthdate), gen -> gen.temporal().localDate().past().as(dob -> dob.format(DateTimeFormatter.BASIC_ISO_DATE)))
  .create();
英文:

As suggested in the comments, it's a good practice to declare the field as aLocalDate instead of a String. If you cannot change that, you can map the date to a string using the as() method:

Student student = Instancio.of(Student.class)
  .generate(field(Student::getBirthdate), gen -> gen.temporal().localDate().past().as(dob -> dob.format(DateTimeFormatter.BASIC_ISO_DATE)))
  .create();

huangapple
  • 本文由 发表于 2023年5月26日 17:08:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76339318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定