Working with dates is a common task in any programming language, and Groovy makes it even simpler with its built-in enhancements over Java. Whether you're displaying a formatted date string to users or converting a user input into a valid Date object, Groovy provides multiple ways to handle date formatting and parsing effectively. In this tutorial, we'll explore how to format and parse dates in Groovy using both traditional SimpleDateFormat and modern Java Time APIs, with practical examples you can use right away.
Preparation
To follow along and run the code examples in this tutorial, you must install Groovy. Here are a few ways to get started quickly:
Option 1: Install Groovy Locally
1. Using SDKMAN (recommended)
If you're on macOS or Linux, run:
curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
sdk install groovy
2. Verify Installation
groovy --version
3. Run Groovy Scripts
Save code to a file like example.groovy, then run:
groovy example.groovy
Option 2: Use Groovy Console (GUI)
Groovy also includes a desktop GUI tool called Groovy Console:
groovyConsole
You can copy and paste any code example into this console and run it interactively.
Option 3: Try Online (No Install)
Use an online Groovy playground like:
1. Using java.text.SimpleDateFormat in Groovy
Groovy seamlessly integrates with Java so that you can use java.text.SimpleDateFormat for both formatting and parsing dates. This is especially useful if you're working with legacy Java code or APIs that require Date objects.
Formatting Date Objects
To format a Date object into a human-readable string, you can use SimpleDateFormat like this:
import java.text.SimpleDateFormat
def date = new Date()
def formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
def formattedDate = formatter.format(date)
println "Formatted Date: $formattedDate"
Output:
Formatted Date: 2025-06-04 14:35:20
Parsing a String into a Date
To convert a date string back into a Date object, use the same SimpleDateFormat with the parse() method:
import java.text.SimpleDateFormat
def dateString = "2025-06-04 14:35:20"
def formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
def parsedDate = formatter.parse(dateString)
println "Parsed Date: $parsedDate"
Output:
Parsed Date: Wed Jun 04 14:35:20 UTC 2025
Things to Watch Out For
- The format string must exactly match the input date string when parsing.
- SimpleDateFormat is not thread-safe, so avoid sharing instances between threads.
2. Using Groovy’s Date.format() Method
Groovy simplifies date formatting by adding the format(String pattern) method directly to the Date class. This makes it easier and more concise than using SimpleDateFormat.
Formatting Dates with Date.format()
You can format a Date instance with a single line of code:
def date = new Date()
def formatted = date.format("dd MMM yyyy")
println "Formatted Date: $formatted"
Output:
Formatted Date: 04 Jun 2025
Using Timezone and Locale (Optional Parameters)
You can also provide optional timezone and locale parameters to format():
def date = new Date()
def formatted = date.format("EEEE, MMMM d, yyyy", TimeZone.getTimeZone("UTC"), Locale.FRANCE)
println "Formatted Date (UTC, French): $formatted"
Output:
Formatted Date (UTC, French): mercredi, juin 4, 2025
Format Patterns
The format string follows the same pattern syntax as SimpleDateFormat. Some common examples:
Pattern | Description | Example Output |
---|---|---|
yyyy-MM-dd |
Year-Month-Day | 2025-06-04 |
dd/MM/yyyy |
Day/Month/Year | 04/06/2025 |
E, MMM dd yyyy |
Day, Month Date Year | Wed, Jun 04 2025 |
hh:mm a |
Hour:Minute AM/PM | 02:30 PM |
Advantages Over SimpleDateFormat
- No need to import or create a formatter
- Cleaner and more Groovy-like
- Supports timezone and locale directly
3. Parsing with Date.parse()
In addition to formatting, Groovy also extends the Date class with a convenient parse(String pattern, String dateString) method, which makes parsing much simpler compared to Java's SimpleDateFormat.
Parsing a Custom Date String
To convert a string into a Date object, use Date.parse() with the appropriate pattern:
def dateString = "04-06-2025"
def parsedDate = Date.parse("dd-MM-yyyy", dateString)
println "Parsed Date: $parsedDate"
Output:
Parsed Date: Wed Jun 04 00:00:00 UTC 2025
Parsing with Time and AM/PM Format
def dateTimeString = "06/04/2025 02:30 PM"
def parsedDateTime = Date.parse("MM/dd/yyyy hh:mm a", dateTimeString)
println "Parsed DateTime: $parsedDateTime"
Output:
Parsed DateTime: Wed Jun 04 14:30:00 UTC 2025
Error Handling
If the date string doesn't match the expected pattern, Groovy will throw a java.text.ParseException. It’s good practice to wrap parsing in a try-catch block:
def invalidDate = "2025/06-04"
try {
def parsed = Date.parse("yyyy-MM-dd", invalidDate)
println "Parsed Date: $parsed"
} catch (Exception e) {
println "Error parsing date: ${e.message}"
}
Output:
Error parsing date: Unparseable date: "2025/06-04"
Quick Tip
Just like format(), parse() uses SimpleDateFormat under the hood, so the same format rules apply.
4. Working with java.time (Java 8+ Time API)
While Groovy enhances Java’s old Date and Calendar classes, it also works beautifully with the newer java.time API was introduced in Java 8. This modern API offers better clarity, immutability, and thread safety.
Groovy 2.5+ supports Java 8 APIs out of the box, so you can work with classes like LocalDate, LocalDateTime, and DateTimeFormatter easily.
Formatting with DateTimeFormatter
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
def now = LocalDateTime.now()
def formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")
def formatted = now.format(formatter)
println "Formatted LocalDateTime: $formatted"
Output:
Formatted LocalDateTime: 2025/06/04 14:45:12
Parsing Strings into LocalDate or LocalDateTime
import java.time.LocalDate
import java.time.format.DateTimeFormatter
def dateString = "2025-06-04"
def formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
def parsedDate = LocalDate.parse(dateString, formatter)
println "Parsed LocalDate: $parsedDate"
Output:
Parsed LocalDate: 2025-06-04
You can do the same with LocalDateTime:
import java.time.LocalDateTime
def dateTimeString = "2025-06-04 15:00"
def formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
def parsedDateTime = LocalDateTime.parse(dateTimeString, formatter)
println "Parsed LocalDateTime: $parsedDateTime"
Formatting with Locale and Timezone
For timezone support, use ZonedDateTime or OffsetDateTime:
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.ZoneId
def zoned = ZonedDateTime.now(ZoneId.of("America/New_York"))
def formatter = DateTimeFormatter.ofPattern("EEE, MMM d yyyy HH:mm z")
println "ZonedDateTime: ${zoned.format(formatter)}"
Output:
ZonedDateTime: Wed, Jun 4 2025 10:45 EDT
Why Use java.time?
- Immutable and thread-safe
- Cleaner API than Date/Calendar
- Better timezone and locale handling
5. Common Date Format Patterns
Whether you're formatting or parsing dates, the pattern you use is key. Groovy uses the same format patterns as Java’s SimpleDateFormat and DateTimeFormatter. Below is a handy reference table of the most commonly used date and time format patterns.
Date and Time Pattern Reference
Pattern | Description | Example Output |
---|---|---|
yyyy |
4-digit year | 2025 |
yy |
2-digit year | 25 |
MM |
2-digit month (01–12) | 06 |
MMM |
Abbreviated month name | Jun |
MMMM |
Full month name | June |
dd |
Day of month (01–31) | 04 |
E or EEE |
Day name short | Wed |
EEEE |
Full day name | Wednesday |
HH |
Hour (00–23) | 14 |
hh |
Hour (01–12) | 02 |
mm |
Minutes (00–59) | 45 |
ss |
Seconds (00–59) | 12 |
a |
AM/PM marker | PM |
z |
Time zone | UTC , PST , EDT |
Z |
RFC 822 timezone offset | +0000 , -0500 |
Example Combinations
Here are a few practical format strings and their sample outputs:
def date = new Date()
println date.format("yyyy-MM-dd") // 2025-06-04
println date.format("EEEE, MMM d, yyyy") // Wednesday, Jun 4, 2025
println date.format("hh:mm:ss a") // 02:45:12 PM
println date.format("yyyyMMdd_HHmmss") // 20250604_144512
These combinations are useful for:
- Displaying dates in UI
- Logging timestamps
- Creating filename-safe timestamps
- Sending ISO-compliant date strings to APIs
6. Real-World Examples
Now that you’ve learned the various ways to format and parse dates in Groovy, let’s apply that knowledge in some practical, real-world scenarios.
1. Generate a Timestamp for a Filename
When saving logs or files, you may want to append a timestamp:
def timestamp = new Date().format("yyyyMMdd_HHmmss")
def filename = "backup_$timestamp.zip"
println "Generated Filename: $filename"
Output:
Generated Filename: backup_20250604_145930.zip
2. Format a Date for Email Templates
Suppose you're sending reminder emails and need a human-readable date:
def eventDate = Date.parse("yyyy-MM-dd", "2025-06-10")
def formatted = eventDate.format("EEEE, MMMM d, yyyy")
println "Reminder: Your appointment is on $formatted"
Output:
Reminder: Your appointment is on Tuesday, June 10, 2025
3. Parse and Reformat API Date Strings
You're working with an API that returns dates in ISO 8601 format, and you want to reformat them:
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
def isoDate = "2025-06-04T14:30:00Z"
def parsed = OffsetDateTime.parse(isoDate)
def reformatted = parsed.format(DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm z"))
println "Formatted API Date: $reformatted"
Output:
Formatted API Date: 04 Jun 2025 14:30 UTC
4. Calculate Days Between Two Dates
import java.time.LocalDate
import java.time.temporal.ChronoUnit
def start = LocalDate.parse("2025-06-01")
def end = LocalDate.parse("2025-06-15")
def daysBetween = ChronoUnit.DAYS.between(start, end)
println "Days Between: $daysBetween"
Output:
Days Between: 14
Summary
In this tutorial, you learned:
- How to format and parse dates using SimpleDateFormat, Groovy’s format() and parse(), and the modern java.time API.
- The most common formatting patterns and how to apply them.
- Real-world examples like timestamping files, creating readable email dates, and parsing ISO strings.
Groovy’s flexibility with date handling means you can pick the approach that works best for your project—concise Groovy methods for quick scripts, or the robust java.time API for enterprise-grade applications.
You can get the full source code on our GitHub.
That's just the basics. If you need more deep learning about Groovy and Grails, you can take the following cheap course:
- Mastering Grails. A Comprehensive Grails Course.
- Groovy Scripting for Developers / Testers
- Introduction to JVM Languages Clojure, Kotlin, and Groovy
Thanks!