Search code examples
c#datetimeunix-timestamp

Remove Seconds from DateTime c#


I have a section of code that converts the unix timestamp value to a standard time, however it is returning hours, minutes, and seconds. I would like it to only return Hours and Minutes.

convertSunriseTime = UnixTimeStampToDateTime(currentSunriseTime).ToString();
convertSunsetTime = UnixTimeStampToDateTime(currentSunsetTime).ToString();

private static TimeSpan UnixTimeStampToDateTime(long unixTimeStamp)
{
    DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);
    return dtDateTime.TimeOfDay;
}

and the moment the varibles convertSunriseTime and convertSunsetTime come back with seconds.


Solution

  • So you want to format your value to show hours and minutes. You can do this:

    convertSunriseTime = UnixTimeStampToDateTime(currentSunriseTime).ToString("hh\\:mm");
    

    Here, the parameter to the ToString() method specifies that you are only interested in getting the hours and minutes parts into the resulting string. This is called a custom TimeSpan format string. There is also a set of standard ones: Standard TimeSpan format strings