/** * Convert Timestamp to RFC 3339 date string format. The output will always be Z-normalized and * uses 3, 6 or 9 fractional digits as required to represent the exact value. Note that Timestamp * can only represent time from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. See * https://www.ietf.org/rfc/rfc3339.txt * * <p>Example of generated format: "1972-01-01T10:00:20.021Z" * * @return The string representation of the given timestamp. * @throws IllegalArgumentException if the given timestamp is not in the valid range. */ public static String toString(Timestamp timestamp) { checkValid(timestamp); long seconds = timestamp.getSeconds(); int nanos = timestamp.getNanos(); StringBuilder result = new StringBuilder(); // Format the seconds part. Date date = new Date(seconds * MILLIS_PER_SECOND); result.append(timestampFormat.get().format(date)); // Format the nanos part. if (nanos != 0) { result.append("."); result.append(formatNanos(nanos)); } result.append("Z"); return result.toString(); }
/** * Convert Duration to string format. The string format will contains 3, 6, or 9 fractional digits * depending on the precision required to represent the exact Duration value. For example: "1s", * "1.010s", "1.000000100s", "-3.100s" The range that can be represented by Duration is from * -315,576,000,000 to +315,576,000,000 inclusive (in seconds). * * @return The string representation of the given duration. * @throws IllegalArgumentException if the given duration is not in the valid range. */ public static String toString(Duration duration) { checkValid(duration); long seconds = duration.getSeconds(); int nanos = duration.getNanos(); StringBuilder result = new StringBuilder(); if (seconds < 0 || nanos < 0) { result.append("-"); seconds = -seconds; nanos = -nanos; } result.append(seconds); if (nanos != 0) { result.append("."); result.append(Timestamps.formatNanos(nanos)); } result.append("s"); return result.toString(); }