java.time
Quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time
, the modern Date-Time API:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.of(LocalDateTime.of(LocalDate.EPOCH, LocalTime.of(12, 0)), ZoneOffset.UTC);
System.out.println(zdt);
}
}
Output:
1970-01-01T12:00Z
ONLINE DEMO
A couple of important notes:
ZonedDateTime#toString
removes seconds and fraction-of-second if they are zero. If you want to display them, you can use DateTimeFormatter
e.g.
String formatted = zdt.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH));
- The
Z
in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC
timezone (which has the timezone offset of +00:00
hours).
Learn more about the modern Date-Time API from Trail: Date Time.
What went wrong with your code?
Quoted below the is description of DateTime(long)
with my emphasis:
Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z using ISOChronology in the default time zone.
Your place, Israel was at an offset of +02:00 hours in 1970 and therefore the DateTime
instance was instantiated with an offset of +02:00 hours.
Demo:
import java.util.concurrent.TimeUnit;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class Main {
public static void main(String[] args) {
DateTime defaultDate = new DateTime(TimeUnit.HOURS.toMillis(12), DateTimeZone.UTC);
System.out.println(defaultDate);
}
}
Output:
1970-01-01T12:00:00.000Z
Another thing, which you might have already noticed from the code, is that DO NOT perform calculations yourself if there is already a standard API (e.g. TimeUnit#toMillis
) available for the same.
* 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.