This answer complements the correct answer by deHaar.
What I need, for example is to get this date: Sunday, 28 de March
2021, 2:00:00
As per the link you have posted, it should be Sunday, 28 March 2021, 03:00:00.
java.time
It is recommended to use java.time
, the modern Date-Time API for date/time operations.
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZoneId zoneId = ZoneId.of("Europe/Madrid");
ZonedDateTime zdt = zoneId.getRules()
.previousTransition(Instant.now())
.getInstant()
.atZone(zoneId);
System.out.println(zdt);
//Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEEE, dd MMMM uuuu, HH:mm:ss", Locale.ENGLISH);
System.out.println(dtf.format(zdt));
}
}
Output:
2021-03-28T03:00+02:00[Europe/Madrid]
Sunday, 28 March 2021, 03:00:00
Learn more about java.time
, 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.