Getting World Time

I am a newbie here, and I am doing some practices. A part of one of them is sending the player a message containing the current world time when he right clicks the air with a clock.
I can’t figure out how to check if the player right clicks the air and how to get world time, and I tried looking in the forums but could not find it.

Help would be appreciated :slight_smile:

Time is stored in the World Properties. So you need to get the players world, and get the properties based on that. One method is:

 Player player = (Player) src;
			    Sponge.getServer().getWorldProperties(player.getWorld().getName()).get().getWorldTime();```

src would be the proper listener you would need to use for to check if they clicked air. Probably an interact event.

Player clicking is InteractBlockEvent. You’re probably looking for InteractBlockEvent.Secondary since it’s right-clicking. This fires for each hand, so you’d check whether the player has the clock in the event-specific hand for that (or just use InteractBlockEvent.Secondary.MainHand and check both). World time is stored in the WorldProperties; get them through World#getProperties(). The method in this case is getWorldTime. Note that it’s not a 0-23999 value; it returns the total number of ticks since the world was initaliized.

So, in summary:

@Listener
public void onInteract(InteractBlockEvent.Secondary e, @First Player p) {
    Optional<ItemStack> stack = p.getItemInHand(e.getHandType());
    if (stack.isPresent() && stack.get().getItem().equals(ItemTypes.CLOCK)) {
        int time = (int) (p.getWorld().getProperties().getWorldTime() % 24000L);
        doSomethingInteresting(time);
    }
}

In case you’re wondering about the int cast, the world time is a long and we wouldn’t want to lose any information by converting to int until it’s definitely 0-23999.