wxkevin
wxkevin

Reputation: 1654

How go I get milliseconds from epoch for a LocalDateTime using a Clock?

I am trying to create a Component that autowires in a java.util.Clock. I am doing this so that I can autowire a Fixed Clock for JUnit testing. I want to provide a method that returns the number of milliseconds since epoch from a provided LocalDateTime. It is not working like I am expecting:

@Component
public class MyClock {
    @Autowired
    Clock clock;

    public long getMilliseconds(LocalDateTime time) {
        ZonedDateTime zdt = ZonedDateTime.of(time, clock.getZone());
        return time.toInstant(zdt.getOffset()).toEpochMilli();
    }
}

So you need an Offset for time.toInstant(). The only way I could see to get the offset is by creating a ZonedDateTime using the clock's zone.

What am I doing wrong or not understanding?

Upvotes: 1

Views: 104

Answers (1)

wxkevin
wxkevin

Reputation: 1654

It turned out that there was a bug somewhere else. This is working properly.

Upvotes: 1

Related Questions