How do I find out what time it is for the computer for day and night cycle?

Okay, so as the time says, I am making a game that is day or night between certain hours. First, I need a way to code for a script to find out what the current time on the computer playing the game is. I want it to be the computer because I want to give the player the option to time travel by changing the computer’s time.
Second, I need a code to check if the time is current within a certain range of the 24-hour cycle.
My idea is If the current time is between 6 pm and 6 am then night equals true.
I would really appreciate help with this. I’m not even sure how to phrase a Google search to find an answer.

var currentDate = DateTime.Now;
var currentTime = currentDate.TimeOfDay;
var nightStart = new TimeSpan(18, 0, 0); // 6 pm
var nightEnd = new TimeSpan(6, 0, 0); // 6 am

var isNightTime = currentTime >= nightStart || currentTime < nightEnd;

if (isNightTime)
    Debug.Log($"Night! Current Time is {currentTime}");
4 Likes

Take your post, add “Unity” somewhere in it, and hand it to your favorite AI. Bing’s Copilot will provide URLs while others may only provide straight up answers. For example here’s Phind’s which is close to @Nad_B 's answer.

https://www.phind.com/search?cache=udbtskt87g5o474i7ae4eqn3

using System;
using UnityEngine;

public class DayNightCycle : MonoBehaviour
{
    void Update()
    {
        // Get the current time
        DateTime currentTime = DateTime.Now;
        TimeSpan currentTimeOfDay = currentTime.TimeOfDay;

        // Define the start and end times for night
        TimeSpan nightStart = new TimeSpan(18, 0, 0); // 6 PM
        TimeSpan nightEnd = new TimeSpan(6, 0, 0); // 6 AM

        // Check if the current time is within the night period
        bool isNight = currentTimeOfDay >= nightStart || currentTimeOfDay < nightEnd;

        // Output the result
        Debug.Log("Is it night? " + isNight);
    }
}
2 Likes