Reputation:
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.HOUR, 8);
calendar.set(calendar.MINUTE, 45);
calendar.set(calendar.SECOND, 00);
Date d = calendar.getTime();
System.out.println(d);
Output is: Wed Oct 05 20:45:00 BST 2011
Can anyone help me with why this is?
Upvotes: 5
Views: 8771
Reputation: 79075
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);
}
}
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.
Upvotes: 3
Reputation: 1500525
Sure - you're setting Calendar.HOUR
which represents the 1-12 "hour of half day". You should be using HOUR_OF_DAY
which is the 0-23 value for the whole day:
calendar.set(Calendar.HOUR_OF_DAY, 8);
Alternatively, use Joda Time which is a much nicer date/time API :)
As an aside, please don't refer to static members via references... it will lead to pain when you call someOtherThread.sleep(...)
and your current thread sleeps...
Upvotes: 8
Reputation: 308031
Calendar.HOUR
is used to set the hour as set on a 12-hour clock.
In other words, you do set the Calendar
to 20:45. It's 8:45 PM.
Use Calendar.HOUR_OF_DAY
to set the 24-hour-clock value.
Upvotes: 9