Groovy中将日期字符串转换为时区时间戳报错问题排查
Let's break down what's going wrong with your code and fix it step by step:
Why Your Code Fails
You're seeing the No signature of method: static java.util.Date.parse() is applicable error for a few key reasons:
Mismatched Date Format vs. String Length
Your input string is201805041235040000000(21 characters long), but you're using the format patternyyyyMMddHHmmsswhich only accounts for 14 characters (year, month, day, hour, minute, second). The extra 7 zeros at the end aren't accounted for in your pattern, so the parser can't match the input to the expected format.Variable Name Typo
In your code, you wroteDate.parse("yyyyMMddHHmmss", timstamp)—note the misspelledtimstampinstead oftimestamp. This would cause Groovy to look for an undefined variable, leading to a type mismatch in the method arguments.java.util.Date Limitations
The oldjava.util.Dateclass doesn't support nanosecond precision (the 7 extra zeros in your string likely represent nanoseconds). Even if you fixed the format, you'd lose that precision usingDate.
Correct Solutions
Option 1: Use Groovy's Date with Truncated Input (Simpler)
If you don't need the nanosecond precision, truncate the input string to a length that Date can handle, then parse and format it:
def inputTimestamp = "201805041235040000000" // Truncate to first 17 characters (includes 3 millisecond digits) def truncatedInput = inputTimestamp.substring(0, 17) def date = Date.parse("yyyyMMddHHmmssSSS", truncatedInput) // Format with timezone def formattedTimestamp = date.format("yyyy-MM-dd'T'HH:mm:ssZ")
Option 2: Use Java 8+ Time API (Recommended for Precision & Timezones)
For proper handling of nanoseconds and explicit timezone control, use Java's modern java.time APIs (Groovy supports these seamlessly):
import java.time.LocalDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter def inputTimestamp = "201805041235040000000" // Define formatter that matches your 21-character input (yyyyMMddHHmmss + 7 nanosecond digits) def formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSSSSS") // Parse to LocalDateTime, then attach a timezone (e.g., UTC or your system timezone) def zonedDateTime = LocalDateTime.parse(inputTimestamp, formatter) .atZone(ZoneId.of("UTC")) // Replace with ZoneId.systemDefault() for local time // Format to your desired timezone-aware string def formattedTimestamp = zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"))
Key Notes
- Always ensure your format pattern exactly matches the length and structure of your input string.
- Prefer the
java.timeAPIs overjava.util.Date—they're more robust, thread-safe, and handle timezones and precision better. - Double-check variable names for typos! Small mistakes like
timstampinstead oftimestampcan cause confusing method signature errors.
内容的提问来源于stack exchange,提问作者Uzair Khan

