Ondrej Bozek
Ondrej Bozek

Reputation: 11481

How to convert String to DurationFieldType?

Hello is there a way to convert String to DurationFieldType in joda time?

For example "years" => DurationFieldType.years();

I'm trying to increase Date with specified number of units like 3 years or 5 monts etc. I've got qunantity (integer) and Time unit type specified with String value.

I'm want to be sure that I didn't overlook something. Best solution I came up with is to use HashMap

Map<String, DurationFieldType> fieldMap = new HashMap<String, DurationFieldType>();
fieldMap.put("year", DurationFieldType.years());
fieldMap.put("month", DurationFieldType.months());
fieldMap.put("day", DurationFieldType.days());
fieldMap.put("week", DurationFieldType.weeks());
fieldMap.put("hour", DurationFieldType.hours());
...
map = Collections.unmodifiableMap(fieldMap);

DateTime from = new DateTime(...);
Period period = new Period().withField(fieldMap.get(someObject.getTimeUnit()), someObject.getDuration());
DateTime to = from.plus(period);

Upvotes: 0

Views: 164

Answers (1)

JodaStephen
JodaStephen

Reputation: 63395

There is no current way to do that lookup.

If you wanted to, you could fork the project on GitHub and add a method to do this - DurationFieldType.of(String) - that does more of less what your code above does. Plus some tests. And then send a pull request ;-)

Upvotes: 2

Related Questions