com.moengage.util.DateFormatUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of condition-evaluator Show documentation
Show all versions of condition-evaluator Show documentation
Condition Evaluator for MoEngage Platform
package com.moengage.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.TimeZone;
public class DateFormatUtil {
static DateFormat[] longDateFormats = new DateFormat[]{new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"),
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"),
new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy"),
new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy zzz"),
new SimpleDateFormat("EEE, MMM dd HH:mm:ss yyyy zzz"),
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"),
new SimpleDateFormat("EEE,dd MMM yyyy HH:mm:ss zzz"),
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:sszzz"),
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss"),
new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss zzz"),
new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS zzz"),
new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"),
new SimpleDateFormat("yyyy/MM/dd HH:mm:ss zzz"),
new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"),
new SimpleDateFormat("yyyy-MM-dd HH:mm"),
new SimpleDateFormat("MMM dd yyyy HH:mm:ss. zzz"),
new SimpleDateFormat("MMM dd yyyy HH:mm:ss zzz"),
new SimpleDateFormat("dd.MM.yyyy HH:mm:ss zzz"),
new SimpleDateFormat("dd MM yyyy HH:mm:ss zzz"),
new SimpleDateFormat("dd MMM yy hh:mm a"),
new SimpleDateFormat("dd.MM.yyyy; HH:mm:ss"),
new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"),
new SimpleDateFormat("dd.MM.yyyy zzz")};
static DateFormat[] shortDateFormats = new DateFormat[]{new SimpleDateFormat("MM-dd")};
public static Date parseDate(String dateTimeStr, TimeZone timeZone) {
Date date = null;
if (dateTimeStr.length() > 5) {
for (DateFormat dateFormat : longDateFormats) {
if (timeZone != null) {
dateFormat.setTimeZone(timeZone);
}
try {
date = dateFormat.parse(dateTimeStr);
break;
} catch (ParseException ignored) {
}
}
if (date == null) {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
if (dateTimeStr.length() <= 10) {
date = Date.from(Instant.ofEpochSecond(Long.parseLong(dateTimeStr)));
} else {
date = Date.from(Instant.ofEpochMilli(Long.parseLong(dateTimeStr)));
}
String dateFormatStr = dateFormat.format(date);
if (timeZone != null) {
dateFormat.setTimeZone(timeZone);
}
date = dateFormat.parse(dateFormatStr);
} catch (Exception ignored) {
date = null;
}
}
} else {
for (DateFormat dateFormat : shortDateFormats) {
if (timeZone != null) {
dateFormat.setTimeZone(timeZone);
}
try {
date = dateFormat.parse(dateTimeStr);
break;
} catch (ParseException ignored) {
}
}
}
return date;
}
}