google / guava

Google core libraries for Java
Apache License 2.0
50.03k stars 10.86k forks source link

Add Duration parsing support to match Abseil C++ and Golang #5456

Open TristonianJones opened 3 years ago

TristonianJones commented 3 years ago

Golang's time.ParseDuration routine parses a very human-readable string format for duration values. This functionality was ported into the Abseil C++ library which makes it easy to consume the same duration strings in both C++ and Golang. Java does have support for Duration parsing to a java.time.Duration, but not in the same format. If the same routines were ported to Guava, then the same format could be used easily across all three languages.

Proposed API change:

package com.google.common.base;

import java.time.Duration;

/**
 * Collection of utilities for working with duration and timestamp values with an emphasis on supporting
 * cross-language conventions.
 */
public final class Time {
  /**
   * Parses input {@code text} into a {@code java.time.Duration} using the duration format string
   * implemented in Golang's {@code time.ParseDuration} and Abseil C++ {@code time::ParseDuration}
   */ 
  public static  Duration parseDuration(CharSequence text) {
    ...
  }
}

For reference: https://github.com/abseil/abseil-cpp/blob/9fde5a6eb081ea080f5aa895102a9154c3a2d09f/absl/time/time.h#L548 https://golang.org/pkg/time/#ParseDuration

cpovirk commented 3 years ago

Thanks. Internally, I notice that we have something like this in the internals of our flag-parsing library (though I notice that ours also supports days; oops...). But I don't see anything publicly accessible.

I do see an internal feature request (issue 132633641, for others at Google) to provide a public API for formatting durations. Parts of the discussion there suggest that we'd be sticking to the ISO 8601 "PT720H" format, but parts suggest that we'd consider something more like the golang/Abseil format.

The bigger question, though, is when/whether we are going to open-source even our existing utilities for java.time, whether into Guava or into another project. In the past, we've opened some feature requests (example) against ThreeTen-Extra. That project seems like the ideal home for such things. Now, I don't think we've absolutely ruled other approaches out. But I would definitely suggest starting there, especially because our team's major push on datetime work is in the past.

TristonianJones commented 3 years ago

I have an implementation of this functionality that I've created for Google CEL (Issue 135933541), but I don't think it belongs in the CEL libraries. I'll follow up with ThreeTen-Extra to see if this is something they're willing to support.

jodastephen commented 3 years ago

FYI. ThreeTen-Extra is still interested in Google's PRs

TristonianJones commented 3 years ago

@jodastephen Thank so much!