Reputation: 193
I have following code
dateTimeFormat = ISODateTimeFormat.dateTimeNoMillis()
and i use dateTimeFormat below
public static String print(Date value) {
return dateTimeFormat.print(value.getTime());
}
And now i get problem, in my print method i put many date instances with + 4 hours time, and after dateTimeFormat.print(value.getTime()); i get time with +3 hour, but one of all date instances become with +4 hours, this error for me.
In all date instances has the same time zone Europe/Moscow
What may be wrong in my case?
Upvotes: 0
Views: 225
Reputation: 79550
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*.
Also, 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.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
public class Main {
public static void main(String[] args) {
System.out.println(print(new Date()));
}
public static String print(Date value) {
return value.toInstant()
.atZone(ZoneId.of("Europe/Moscow"))
.truncatedTo(ChronoUnit.SECONDS)
.toOffsetDateTime()
.toString();
}
}
Output:
2021-06-20T16:18:56+03:00
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: 2
Reputation: 1503180
In all date instances has the same time zone Europe/Moscow
A Date
instance doesn't have a time zone - it's just an instant in time. But you should probably specify the time zone for your formatter, e.g.
dateTimeFormat = ISODateTimeFormat
.dateTimeNoMillis()
.withZoneUTC();
If you want a value which does know about a time zone, you should use DateTime
instead of Date
.
Upvotes: 2