C# asp.net core 2.2 – Get current date time – Not Accurate

I tried everything to get the current year/month/date/hour but It doesn’t work. I always get data 1 hour behind. So if it’s 17:00 in the Netherlands, I get 16:00. I have tried so many things, but I can’t get this fixed.. is it a bug?

I Tried this:

string dateTimeNowPlusForecaseHour = DateTimeOffset.Now.ToLocalTime().AddHours(hour).ToString("yyyyMMddhh"); 

And this:

string dateTimeNowPlusForecaseHour = DateTimeOffset.UtcNow.ToLocalTime().AddHours(hour).ToString("yyyyMMddhh");

And this:

string dateTimeNowPlusForecaseHour = DateTimeOffset.UtcNow.ToLocalTime().AddHours(hour).ToString("yyyyMMddhh");

And this:

string dateTimeNowPlusForecaseHour = DateTimeOffset.Now.AddHours(hour).ToString("yyyyMMddhh"); 

And this:

        public string GetForecastTime(int hour)
    {
        // Take amount of seconds elapsed since 1970
        var amountOfSecondsElapsedSince1970 = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();

        // Make a Datetime variable (1970 is the start)
        System.DateTime dateTimeNowString = new DateTime(1970, 1, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);

        // Add amountOfSecondsElapsedSince1970 to the date time starting at 1970, + the amount of hours (for each forecast so 0, 1, and 2)
        dateTimeNowString = dateTimeNowString.AddSeconds(amountOfSecondsElapsedSince1970).AddHours(hour).ToLocalTime();

        // This is the dateTime
        string dateRealWeatherForecastTimee = dateTimeNowString.ToString("yyyyMMddhh");

        return dateRealWeatherForecastTimee;
    }

Nothing seems to work.. Please help me out with this one.

Update:

I tried the following line on a new asp.net core console project (rather than the project I’m working on):

    string dateTimeNowPlusForecaseHour = DateTime.Now.AddHours(hour).ToString("yyyyMMddhh");

That works! But why doesn’t it work for the project I’m working on?

Update2.0:
When I view my timezone of the project, I get GMT which is wrong. When I create a new asp.net core console project and view the timezone, I get w. europe, which gives me the correct time… Why is the timezone wrong? Shouldn’t that be correct automatically?

Leave a Reply

Your email address will not be published. Required fields are marked *