3

How can I initialize an instant type?

I tried this:

Instant instant = new Instant();

But doesn't work..

I need it because after on Freemarker I have to do this:

[#assign dateFormated = newDate.from(instant.ofEpochSecond(data.time.seconds))/]
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Tonino Fernandez
  • 441
  • 4
  • 12
  • There are several methods available to initialize an `Instant`. You could use `Instant.now()`, `Instant.ofEpochMilli`, etc. Just have a look at the documentation for the class. – Ben May 17 '18 at 09:02
  • 3
    Don't write "doesn't work" but rather "doesn't compile". In case of simple compile errors, you should really consult the documentation and look which static class members are available if there is no public constructor. The class `Instant` offers a plenty of static factory methods. – Meno Hochschild May 17 '18 at 09:10
  • Seen your other question, why not create a `java.util.Date`? – Jasper de Vries May 17 '18 at 09:12
  • 2
    @JasperdeVries `Date` is long outdated (no pun intended) and poorly designed, and most of its methods and constructors are deprecated because they are unreliable across time zones. It’s very distinctively technology from another millennium. `java.time`, the modern Java date and time API that `Instant` belongs to, is so much nicer to work with. – Ole V.V. May 17 '18 at 09:47
  • @OleV.V. true, but it does make life easier when working with FreeMarker. See also https://stackoverflow.com/questions/32063276/java-time-java-8-support-in-freemarker – Jasper de Vries May 17 '18 at 09:51
  • See also https://github.com/amedia/freemarker-java-8 – Jasper de Vries May 17 '18 at 10:22
  • @GhostCat I'm doing what you have put it here but I'm getting an error, could you see this, please? https://stackoverflow.com/questions/50389281/freemarker-error-expected-hash – Tonino Fernandez May 17 '18 at 10:58
  • Sorry, I am also no expert on freemaker. The one thing is strange though: you are using `instant.ofEpoch...` ... I assume you call the static method, but then it should be `Instant.ofEpoch...` ?! – GhostCat May 17 '18 at 11:15
  • @GhostCat well, I'm callting "instant.ofEpoch" because I defined that instant is a variable that I initialized, I'm also not expert on this... but I think that is something like that. Thanks for ur time – Tonino Fernandez May 17 '18 at 11:38
  • As of doing this in FreeMarker templates, see your other question: https://stackoverflow.com/questions/50389281/freemarker-error-expected-hash – ddekany May 17 '18 at 22:09

1 Answers1

10

Straight from the Oracle tutorial:

import java.time.Instant;

Instant timestamp = Instant.now()

You will find other explanations there as well.

Thus the real answer is: by doing some research. Especially the standard library classes come with extensive amounts of Javadoc explaining all of their aspects and most often, there are plenty of tutorials out there, too.

GhostCat
  • 137,827
  • 25
  • 176
  • 248