He takes advantage of the cloak of darkness to lure the giants (robbers, in other variants) to the castle to kill them. This type of narrative is classified as another tale type: AaTh 723*, "Hero Binds Midnight, Dawn, and Midday".
In some variants of ATU 304, before the hero enters the castle of the princesses and kills the giants, he meets a personified being (an old man or an old woman) that controls the day and night cycle, either with balls or yarns (a black one symbolizing the night, and a white one representing the day). The hero then ties this being up a tree so that it remains nighttime.