C# 如何将 24 小时格式的 TimeSpan 转换为 12 小时格式的 TimeSpan?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10123426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:31:35  来源:igfitidea点击:

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

c#

提问by user1108069

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 and msdn, but didn't solve this problem, can anyone help me? Thanks in advance.

我将 TimeSpan 数据表示为 24 小时格式,例如 14:00:00,我想将其转换为 12 小时格式,下午 2:00,我在 google 上搜索并在 stackoverflow 和 msdn 中找到了相关内容,但没有解决这个问题,谁能帮帮我?提前致谢。

UpdateSeems that it's possible to convert 24-hour format TimeSpan to String, but impossible to convert the string to 12-hour format TimeSpan :(

更新似乎可以将 24 小时格式的 TimeSpan 转换为字符串,但无法将字符串转换为 12 小时格式的 TimeSpan :(

But I still got SO MANY good answers, thanks!

但是我还是得到了很多好的答案,谢谢!

采纳答案by M.Babcock

TimeSpanrepresents a time intervalnot a time of day. The DateTimestructure is more likely what you're looking for.

TimeSpan表示时间间隔而不是一天中的时间。该DateTime结构更可能是您正在寻找的。

回答by Steve Danner

Assuming you are staying in a 24 hour range, you can achieve what you want by subtracting the negative TimeSpanfrom Today's DateTime(or any date for that matter), then strip the date portion:

假设您保持在 24 小时范围内,您可以通过TimeSpan从今天DateTime(或任何日期)中减去负数来实现您想要的结果,然后去除日期部分:

DateTime dt = DateTime.Today;
dt.Subtract(-TimeSpan.FromHours(14)).ToShortTimeString();

Yields:

产量:

2:00 PM

下午 2:00

回答by Tim Schmelter

TimeSpanrepresents a time interval (a difference between times), not a date or a time, so it makes little sense to define it in 24 or 12h format. I assume that you actually want a DateTime.

TimeSpan表示时间间隔(时间之间的差异),而不是日期或时间,因此以 24 或 12 小时格式定义它没有多大意义。我假设您实际上想要一个DateTime.

For example 2 PM of today:

例如今天下午 2 点:

TimeSpan ts = TimeSpan.FromHours(14);
DateTime dt = DateTime.Today.Add(ts);

Then you can format that date as you want:

然后您可以根据需要格式化该日期:

String formatted = String.Format("{0:d/M/yyyy hh:mm:ss}", dt); // "12.4.1012 02:00:00" - german (de-DE)

http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.100%29.aspx

http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.100%29.aspx

回答by Lam Tran Duy

You need to convert the TimeSpan to a DateTime object first, then use whatever DateTime formatyou need:

您需要先将 TimeSpan 转换为 DateTime 对象,然后使用您需要的任何DateTime 格式

var t = DateTime.Now.TimeOfDay;

Console.WriteLine(new DateTime(t.Ticks).ToString("hh:mm:ss tt"));

ToShortTimeString()would also work, but it's regional-settings dependent so it would not display correctly (or correctly, depending on how you see it) on non-US systems.

ToShortTimeString()也可以工作,但它取决于区域设置,因此它不会在非美国系统上正确显示(或正确显示,取决于您如何看待它)。

回答by sarwar026

String formatted = yourDateTimeValue.ToString("hh:mm:ss tt");

回答by Krunal Mevada

Try This Code:

试试这个代码:

int timezone = 0;

This string gives 12-hours format

此字符串提供 12 小时格式

string time = DateTime.Now.AddHours(-timezone).ToString("hh:mm:ss tt");

This string gives 24-hours format

此字符串提供 24 小时格式

string time = DateTime.Now.AddHours(-timezone).ToString("HH:mm:ss tt");

回答by Martin Liversage

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

(在一个答案中总结我分散的评论。)

First you need to understand that TimeSpanrepresents a time interval. This time interval is internally represented as a count of ticks an not the string 14:00:00nor the string 2:00 PM. Only when you convert the TimeSpanto 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.

首先你需要了解它TimeSpan代表一个时间间隔。此时间间隔在内部表示为滴答计数,而不是字符串14:00:00或字符串2:00 PM。只有当您将 转换TimeSpan为字符串时,讨论两种不同的字符串表示形式才有意义。从一种表示切换到另一种表示不会改变或转换存储在TimeSpan.

Writing time as 2:00 PMinstead of 14:00:00is about date/time formatting and culture. This is all handled by the DateTimeclass.

写时间2:00 PM而不是14:00:00关于日期/时间格式和文化。这一切都由DateTime班级来处理。

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

然而,即使TimeSpan表示一个时间间隔,它也非常适合表示一天中的时间(DateTime.TimeOfDay返回 a TimeSpan)。因此,将其用于该目的并非没有道理。

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

要执行所描述的格式化,您需要依赖于 的格式化逻辑DateTime或简单地创建您自己的格式化代码。

  • 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 ToStringare documented on the Custom Date and Time Format Stringspage on MSDN. It is important to specify a CultureInfothat uses the desired AM/PM designator. Otherwise the ttformat 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.

  • 使用DateTime

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

    使用 in 的格式说明符ToString记录在 MSDN上的自定义日期和时间格式字符串页面上。指定CultureInfo使用所需 AM/PM 指示符的a 很重要。否则,tt格式说明符可能会被空字符串替换。

  • 使用自定义格式:

    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);
    

    诚然,这个解决方案比第一种方法复杂得多。

回答by Abdullah Samo

It is very simple, Let's suppose we have an object tsof TimesSpan : TimeSpan ts = new TimeSpan();and suppose it contains some value like 14:00:00 Now first convert this into a string and then in DateTime as following:

这很简单,假设我们有一个TimesSpan的对象tsTimeSpan ts = new TimeSpan();并假设它包含一些像 14:00:00 这样的值现在首先将其转换为字符串,然后在 DateTime 中,如下所示:

TimeSpan ts = new TimeSpan(); // this is object of TimeSpan and Suppose it contains
                              // value 14:00:00
string tIme = ts.ToString(); // here we convert ts into String and Store in Temprary
                             // String variable.
 DateTime TheTime = new DateTime(); // Creating the object of DateTime;
 TheTime = Convert.ToDateTime(tIme); // now converting our temporary string into DateTime;
 Console.WriteLine(TheTime.ToString(hh:mm:ss tt));

this will show the Result as: 02:00:00 PM

这将显示结果为:02:00: 00 PM