0

Hi Is there any way to check whether the given string is epoch millis or not

The below code from java.time package converts to EpochMillis.

I am looking for isEpochMillis to return a boolean condition.

Is there any ready made api from apache commons or google guava to check this ? just like isDouble isLong etc...

/**
     * Obtains an instance of {@code Instant} using milliseconds from the
     * epoch of 1970-01-01T00:00:00Z.
     * <p>
     * The seconds and nanoseconds are extracted from the specified milliseconds.
     *
     * @param epochMilli  the number of milliseconds from 1970-01-01T00:00:00Z
     * @return an instant, not null
     * @throws DateTimeException if the instant exceeds the maximum or minimum instant
     */
    public static Instant ofEpochMilli(long epochMilli) {
        long secs = Math.floorDiv(epochMilli, 1000);
        int mos = (int)Math.floorMod(epochMilli, 1000);
        return create(secs, mos * 1000_000);
    }
user3190018
  • 890
  • 13
  • 26
  • Huh? Any integer is a valid timestamp. Zero is the epoch itself. Minus a billion billion billion is... quite a long time ago. – Michael Jul 31 '19 at 16:05

3 Answers3

0

Any positive whole number is theoretically valid. You can add constraints based on your own knowledge of the domain. For example: no timestamps in the future, hence all numbers greater than Instant.now().toEpochMillis() are invalid.

  • I know these things, I just need ready made api with apache commons or guava to check whether passed long is parsable or not – user3190018 Jul 31 '19 at 18:14
  • Is there any ready made api from apache commons or google guava to check this ? – user3190018 Jul 31 '19 at 21:11
  • AFAIK no, as mentioned in other comments you have Long.parseLong to verify that the string is a number, and then compare it with Instant.now(). This can be easily wrapped in a utility class in your project. – Issa Khoury Aug 01 '19 at 17:47
0

As the javadoc says, epochMilli is number of milliseconds since 1970-01-01. All long values are valid epochMillis. It comes down to down to which dates you allow. That will then be your range.

-2 would result in 1969-12-31T23:59:59.998Z.

user1478293
  • 46
  • 1
  • 5
0

There is not, but here is an implementation of that method:

public static boolean isEpochMillis(long epochMilli) { 
  return true; 
}

Of course, you might find that this method is unnecessary, now that you see its implementation.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413