Tuesday 20 August 2019

Java Clock class does not give me the current time

Answer


Answer





I try to use the Clock class to get the current time.



public class TestClock {
public static void main(String[] args) {
Clock c = Clock.systemDefaultZone();
System.out.println(c.instant());
}
}



But the problem is that it does not give me the current time,
but it gives:




(the current time - 3 hours)




So I decided to be more precise and to specify to the program the city where I live in. (Beirut)




public class TestClock {
public static void main(String[] args) {
ZoneId zone = ZoneId.of("Asia/Beirut");
Clock c = Clock.system(zone);
System.out.println(c.instant());
}
}



Also, it gives me:




(the current time - 3 hours).




So where is the problem?



Note: In Lebanon-Beirut the time +3 Greenwich, is there a relation between this information and my problem?


Answer




Like @Erwin Bolwidt pointed out please use ZonedDateTime and pass the zone.



public class TestClock {
public static void main(String[] args) {
ZoneId zone = ZoneId.of("Asia/Beirut");
ZonedDateTime zdt = ZonedDateTime.now(zone);
System.out.println(zdt);
}
}



Result:



2019-06-11T10:07:20.447+03:00[Asia/Beirut]

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...