1

I am trying to compare two dates in C#. One is a sunset date and one is the current date. I am trying to determine whether it's after or before sunset. I have two dates like that:

  1. 2021-12-02 16:19 (Current Date)
  2. 05:55:50 PM (Sunset Date)

I have been trying to compare them this way:

var currentTime = DateTime.ParseExact(Weather.location.localtime, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture).TimeOfDay;
var sunsetTime = DateTime.ParseExact(SunriseSunset.results.sunset, "hh:mm:ss tt", CultureInfo.InvariantCulture).TimeOfDay;

bool sunStillUp = currentTime < sunsetTime;

I know that the error means that the given dates are in incorrect format, however I cannot see how..

Weather.location.localtime is this (getting data from an api):

enter image description here

And SunriseSunset.results.sunset is this (getting data from an api):

enter image description here

  • 1
    What **date** do you think `05:55:50 PM` is? – HardCode Dec 02 '21 at 17:32
  • Allright @HardCode, addded a date in front of it: now it's `2021-12-02 05:55:50 PM`. Then the code is : `var sunsetTime = DateTime.ParseExact(sunset, "yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture).TimeOfDay;` But it still does not work – GetTwoBirdsStonedAtOnce Dec 02 '21 at 17:42
  • 1
    `DateTime.ParseExact("2021-12-02 05:55:50 PM", "yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture)` works fine for me. But the last screenshot shows that you may get a 1-digit hour, so you probably should use `yyyy-MM-dd h:m:s tt` – Klaus Gütter Dec 02 '21 at 18:41
  • You're right, with the yyyy-MM-dd h:m:s tt format it works! Thanks for pointing that out! – GetTwoBirdsStonedAtOnce Dec 02 '21 at 19:08

0 Answers0