Elasticsearch 2.4 Groovy脚本:Unix时间戳转YYYYMM格式
Solution for Converting Unix Timestamp to YYYYMM in Elasticsearch 2.4 Groovy Script
Got it, let's fix this timestamp formatting issue you're facing with Elasticsearch 2.4 and Groovy. Here's a straightforward way to convert your integer Unix timestamp into the YYYYMM format (with leading zero for single-digit months):
Working Groovy Script Code
// Get the raw Unix timestamp from the document def unixTimestamp = doc['created_unix_timestamp'].value; // Convert timestamp to a Date object // Important: Multiply by 1000L if your timestamp is in SECONDS (most common case) // Skip the *1000L if it's already in MILLISECONDS def eventDate = new Date(unixTimestamp * 1000L); // Set up the date formatter for YYYYMM format def dateFormatter = new java.text.SimpleDateFormat("yyyyMM"); // Optional but critical: Set your desired time zone to avoid month shifts due to time zone offsets dateFormatter.setTimeZone(java.util.TimeZone.getTimeZone("UTC")); // Format the date and return it (as string or integer) def formattedDate = dateFormatter.format(eventDate); // If you need the result as an integer instead of string, uncomment the line below // return Integer.parseInt(formattedDate); return formattedDate;
Key Notes:
- Time Zone Handling: Always set a time zone explicitly (like UTC) to prevent unexpected month changes caused by your cluster's default time zone. For example, a timestamp just after midnight in UTC might fall into the previous month in a time zone west of UTC.
- Timestamp Unit: Double-check if your
created_unix_timestampis stored in seconds or milliseconds. Most Unix timestamps are seconds, so multiplying by1000Lconverts it to the milliseconds required by Java'sDateclass. - Return Type: The script returns a string by default (e.g.,
"201804"). If you need an integer result, useInteger.parseInt(formattedDate)as shown in the commented line.
Example Test
For the timestamp 1522703848 (which is 2018-04-03 01:37:28 UTC), this script will output "201804" (or 201804 as an integer if you use the parse line).
内容的提问来源于stack exchange,提问作者JVK
相关产品推荐
相关产品推荐

