package org.gbif.occurrence.hive.udf;

import org.gbif.occurrence.common.download.DownloadUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

/**
 * A simple UDF for Hive to convert a date/long to an string in ISO 8601 format.
 * If the input value is null or can't be parsed, and empty string is returned.
 */
@Description(
  name = "toISO8601",
  value = "_FUNC_(field)")
public class ToISO8601UDF extends UDF {

  private final Text text = new Text();


  public Text evaluate(Text field) {
    if (field == null) {
      text.set("");
    } else {
      try {
        text
          .set(new SimpleDateFormat(DownloadUtils.ISO_8601_FORMAT).format(new Date(Long.parseLong(field.toString()))));
      } catch (NumberFormatException e) {
        text.set("");
      }
    }

    return text;
  }
}

@@ -126,16 +126,71 @@
 Format;%0A
+import java.time.Instant;%0Aimport java.time.ZoneOffset;%0A
 import j
@@ -648,17 +648,16 @@
 ext();%0A%0A
-%0A
   public
@@ -771,43 +771,11 @@
 text
-%0A          .set(new SimpleDateForma
+.se
 t(Do
@@ -805,17 +805,16 @@
 RMAT
-)
 .format(
 new 
@@ -813,16 +813,28 @@
 mat(
-new Date
+Instant.ofEpochMilli
 (Lon
@@ -863,16 +863,39 @@
 ring()))
+.atZone(ZoneOffset.UTC)
 ));%0A    

Update time formatter.