0

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?

user9152856
  • 99
  • 1
  • 9
  • 6
    An instant has no timezone. – luk2302 Jun 11 '19 at 07:03
  • 2
    Use [`ZonedDateTime.now()`](https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#now-java.time.Clock-). [`Instant`](https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html) doesn't have a time zone, or it is in the UTC time zone, depending on how you look at it. – Erwin Bolwidt Jun 11 '19 at 07:04
  • Yes, you are right, but I still have one question: Why we can pass zone as a parameter to the clock objects, while there is no method in the clock class that gives time with time zone? – user9152856 Jun 11 '19 at 07:27

1 Answers1

1

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]
Community
  • 1
  • 1
Alexpandiyan Chokkan
  • 1,025
  • 1
  • 10
  • 30
  • Yes, you are right, but I still have one question: Why we can pass zone as a parameter to the clock objects, while there is no method in the clock class that gives time with time zone? – user9152856 Jun 11 '19 at 07:17
  • Please read about the `Instant` in java official doc https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html – Alexpandiyan Chokkan Jun 11 '19 at 07:28