java.time
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*.
Solution using java.time
, the modern Date-Time API:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
Instant instant = OffsetDateTime.now(ZoneOffset.UTC)
.withHour(8)
.withMinute(45)
.withSecond(0)
.toInstant();
System.out.println(instant);
}
}
ONLINE DEMO
An Instant
represents an instantaneous point on the timeline in UTC. The Z
in the output is the timezone designator for a zero-timezone offset. It stands for Zulu and specifies the Etc/UTC
timezone (which has the timezone offset of +00:00
hours).
For any reason, if you need to convert this object of Instant
to an object of java.util.Date
, you can do so as follows:
Date date = Date.from(instant);
Note: Most likely, you would like the fraction-of-second too to be zero. If yes, just add .withNano(0)
in the existing code as shown below:
OffsetDateTime.now(ZoneOffset.UTC)
.withHour(8)
.withMinute(45)
.withSecond(0)
.withNano(0)
.toInstant();
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.