The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Demo using java.time
, the modern Date-Time API:
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
System.out.println(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(5)
.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss", Locale.ENGLISH)));
}
}
Output:
2021-06-17T09:45:14
ONLINE DEMO
If you do not want to use the static methods like ZonedDateTime.now
, DateTimeFormatter.ofPattern
etc. (as you have commented), you can do it as shown below:
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
System.out.println(new Date().toInstant().plusSeconds(5).atZone(ZoneOffset.UTC).format(
new DateTimeFormatterBuilder().appendPattern("uuuu-MM-dd'T'HH:mm:ss").toFormatter(Locale.ENGLISH)));
}
}
ONLINE DEMO
Based on this, you can create your expression as follows:
Expression exp = parser.parseExpression("new Date().toInstant().plusSeconds(5).atZone(ZoneOffset.UTC).format(new DateTimeFormatterBuilder().appendPattern(\"uuuu-MM-dd'T'HH:mm:ss\").toFormatter(Locale.ENGLISH))");
For any reason, if you need to convert this object of Instant
to an object of java.util.Date
, you can do so using Date#from
:
Date.from(new Date().toInstant().plusSeconds(5))
Alternatively,
new Date(new Date().toInstant().plusSeconds(5).toEpochMilli())
However, you need SimpleDateFormat
to format an object of java.util.Date
and the problem with SimpleDateFormat
is that it uses the JVM's timezone by default. If you need the date-time in a particular timezone, you need to set the timezone to SimpleDateFormat
explicitly beforehand e.g.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = sdf.format(date); // date is an instance of java.util.Date
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.