You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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_timestamp is stored in seconds or milliseconds. Most Unix timestamps are seconds, so multiplying by 1000L converts it to the milliseconds required by Java's Date class.
  • Return Type: The script returns a string by default (e.g., "201804"). If you need an integer result, use Integer.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:40:19