How to load a DATETIME object from a YAML file?

I am using the JODA TIME library to save DATETIME. Before running tests, I need to set up test data. So I have a yaml file in which I defined test data with dates that I hoped to convert to DATETIME objects, but they are not.

I am using Play Framework 2.0. Any idea how I can convert the YAML date to a real DATETIME object.

This is what my yaml file looks like

users: - !!models.User createdOn: 2001-09-09T01:46:40Z fName: Mike lName: Roller 
+4
source share
2 answers

Adapted from snakeyaml WIKI project . Examples here .

How to disassemble JodaTime

Since JodaTime is not a JavaBean (because it does not have an empty constructor), it requires additional processing when parsing:

 private class ConstructJodaTimestamp extends ConstructYamlTimestamp { public Object construct(Node node) { Date date = (Date) super.construct(node); return new DateTime(date, DateTimeZone.UTC); } } 

When a JodaTime instance is a JavaBean property, you can use the following:

 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); } } } } 
+1
source
 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; } 

use method

 getDateFromFile("createdOn:", pathToFile) 
0
source

Source: https://habr.com/ru/post/1443998/


All Articles