how to convert 24-hour format TimeSpan to 12-hour format TimeSpan?

前端 未结 8 986
陌清茗
陌清茗 2021-01-04 05:17

I have TimeSpan data represented as 24-hour format, such as 14:00:00, I wanna convert it to 12-hour format, 2:00 PM, I googled and found something related in stackoverflow a

8条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 05:39

    (Summing up my scattered comments in a single answer.)

    First you need to understand that TimeSpan represents a time interval. This time interval is internally represented as a count of ticks an not the string 14:00:00 nor the string 2:00 PM. Only when you convert the TimeSpan to a string does it make sense to talk about the two different string representations. Switching from one representation to another does not alter or convert the tick count stored in the TimeSpan.

    Writing time as 2:00 PM instead of 14:00:00 is about date/time formatting and culture. This is all handled by the DateTime class.

    However, even though TimeSpan represents a time interval it is quite suitable for representing the time of day (DateTime.TimeOfDay returns a TimeSpan). So it is not unreasonable to use it for that purpose.

    To perform the formatting described you need to either rely on the formatting logic of DateTime or simply create your own formatting code.

    • Using DateTime:

      var dateTime = new DateTime(timeSpan.Ticks); // Date part is 01-01-0001
      var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
      

      The format specifiers using in ToString are documented on the Custom Date and Time Format Strings page on MSDN. It is important to specify a CultureInfo that uses the desired AM/PM designator. Otherwise the tt format specifier may be replaced by the empty string.

    • Using custom formatting:

      var hours = timeSpan.Hours;
      var minutes = timeSpan.Minutes;
      var amPmDesignator = "AM";
      if (hours == 0)
        hours = 12;
      else if (hours == 12)
        amPmDesignator = "PM";
      else if (hours > 12) {
        hours -= 12;
        amPmDesignator = "PM";
      }
      var formattedTime =
        String.Format("{0}:{1:00} {2}", hours, minutes, amPmDesignator);
      

      Admittedly this solution is quite a bit more complex than the first method.

提交回复
热议问题