When you have a complicated problem, it's often useful to break it up into simpler steps:
Step 1: If necessary, convert the sun/moonrise/set times into proper datetime values that you can do arithmetic with. Second since the Unix epoch (or minutes since the start of the millennium, or whatever) will do, but if your language has an appropriate datetime class or type, I'd recommend using that.
Since this conversion is, presumably, the same for all the timestamps, you can write a single function that will do it for an arbitrary time value, and call it for each of your inputs.
Step 2: Find the start and end times of the moonlight period(s).
If you want the moonlight hours for one night, then you can calculate the start and end of the moonlight period as:
start = max(moonrise, sunset)
end = min(sunrise, moonset)
If you really need the moonlight hours for one calendar day, it's a bit more complicated, since there may be two separate moonlight periods. You can calculate their respective start and end times as:
start1 = max(moonrise1, sunset1, midnight)
end1 = min(sunrise1, moonset1)
start2 = max(moonrise2, sunset2)
end1 = min(sunrise2, moonset2, midnight + 24 hours)
where the variable names ending in 1
denote the respective times for the night before the given day, and the variable names ending in 2
denote the respective times for the night after the given day.
Step 3: Calculate the length(s) of the moonlight period(s).
This is just simple datetime subtraction. Note that the subtraction might give a negative value, if the moon is not visible at all on a given night, in which case you should clamp the result to zero.
If you're doing the calculation for a specific calendar date, you should repeat this for both the previous and the next night, and then add the (non-negative) results together.