【问题标题】:How to load DATETIME object from YAML file?如何从 YAML 文件加载 DATETIME 对象?
【发布时间】:2012-11-04 21:44:05
【问题描述】:
我正在使用 JODA TIME 库来持久化 DATETIME。在我运行测试之前,我需要设置测试数据。所以我有一个 yaml 文件,我在其中定义了带有日期的测试数据,我希望这些数据可以转换为 DATETIME 对象,但事实并非如此。
我正在使用 Play Framework 2.0。知道如何将 YAML 日期转换为真正的 DATETIME 对象。
这是我的 yaml 文件的样子
users:
- !!models.User
createdOn: 2001-09-09T01:46:40Z
fName: Mike
lName: Roller
【问题讨论】:
标签:
java
playframework-2.0
yaml
jodatime
playframework-2.1
【解决方案1】:
取自snakeyaml project WIKI。例如here。
如何解析 JodaTime
由于 JodaTime 不是 JavaBean(因为它没有空的构造函数),所以在解析时需要一些额外的处理:
private class ConstructJodaTimestamp extends ConstructYamlTimestamp {
public Object construct(Node node) {
Date date = (Date) super.construct(node);
return new DateTime(date, DateTimeZone.UTC);
}
}
当 JodaTime 实例是 JavaBean 属性时,您可以使用以下内容:
Yaml y = new Yaml(new JodaPropertyConstructor());
class JodaPropertyConstructor extends Constructor {
public JodaPropertyConstructor() {
yamlClassConstructors.put(NodeId.scalar, new TimeStampConstruct());
}
class TimeStampConstruct extends Constructor.ConstructScalar {
@Override
public Object construct(Node nnode) {
if (nnode.getTag().equals("tag:yaml.org,2002:timestamp")) {
Construct dateConstructor = yamlConstructors.get(Tag.TIMESTAMP);
Date date = (Date) dateConstructor.construct(nnode);
return new DateTime(date, DateTimeZone.UTC);
} else {
return super.construct(nnode);
}
}
}
}
【解决方案2】:
org.joda.time.DateTime getDateFromFile(final String string, final String path) throws IOException {
final BufferedReader f = new BufferedReader(new FileReader(path));
String s;
final Pattern pattern = Pattern.compile(".+" + string + ".+([0-9\\-:ZT]+)");
while ((s = f.readLine()) != null)
{
final Matcher m = pattern.matcher(s);
if (m.matches())
{
return ISODateTimeFormatter.dateTimeNoMillis().parseDateTime(m.group(1));
}
}
return null;
}
使用方法
getDateFromFile("createdOn:", pathToFile)