使用 C# 将时间跨度值转换为格式“hh:mm Am/Pm”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13044603/
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-10 01:26:37  来源:igfitidea点击:

Convert time span value to format "hh:mm Am/Pm" using C#

c#.net

提问by Amit Kumar

I have a value stored in variable of type System.TimeSpanas follows.

我有一个存储在类型变量中的值System.TimeSpan,如下所示。

System.TimeSpan storedTime = 03:00:00;

Can I re-store it in another variable of type Stringas follows?

我可以将它重新存储在另一个类型的变量中String吗?

String displayValue = "03:00 AM";

And if storedTimevariable has the value of

如果storedTime变量的值为

storedTime = 16:00:00;

then it should be converted to:

那么它应该转换为:

String displayValue = "04:00 PM";

采纳答案by Asif Mushtaq

You can do this by adding your timespan to the date.

您可以通过将时间跨度添加到日期来做到这一点。

TimeSpan timespan = new TimeSpan(03,00,00);
DateTime time = DateTime.Today.Add(timespan);
string displayTime = time.ToString("hh:mm tt"); // It will give "03:00 AM"

回答by Tim Schmelter

You can add the TimeSpanto a DateTime, for example:

您可以将TimeSpan加到 a DateTime,例如:

TimeSpan span = TimeSpan.FromHours(16);
DateTime time = DateTime.Today + span;
String result = time.ToString("hh:mm tt");

Demo: http://ideone.com/veJ6tT

演示:http: //ideone.com/veJ6tT

04:00 PM

Standard Date and Time Format Strings

标准日期和时间格式字符串

回答by Henk Holterman

string displayValue="03:00 AM";

This is a point in time, not a duration(TimeSpan).

这是一个时间点,而不是持续时间(TimeSpan)。

So something is wrong with your basic design or assumptions.

所以你的基本设计或假设有问题。

If you do want to use it, you'll have to convert it to a DateTime (point in time) first. You can format a DateTime without the date part, that would be your desired string.

如果您确实想使用它,则必须先将其转换为 DateTime(时间点)。您可以格式化没有日期部分的 DateTime,这将是您想要的字符串。

TimeSpan t1 = ...;
DateTime d1 = DateTime.Today + t1;               // any date will do
string result = d1.ToString("hh:mm:ss tt");

storeTime variable can have value like
storeTime=16:00:00;

storeTime 变量可以具有类似的值
storeTime=16:00:00;

No, it can have a value of 4 o'clock but the representation is binary, a TimeSpan cannot record the difference between 16:00and 4 pm.

不,它可以有4点的值,但表示是二进制的,时间跨度不能记录之间的差别16:004 pm

回答by Habib

Parse timespan to DateTime and then use Format ("hh:mm:tt"). For example.

将时间跨度解析为 DateTime,然后使用 Format ("hh:mm:tt")。例如。

TimeSpan ts = new TimeSpan(16, 00, 00);
DateTime dtTemp = DateTime.ParseExact(ts.ToString(), "HH:mm:ss", CultureInfo.InvariantCulture);
string str = dtTemp.ToString("hh:mm tt");

strwill be:

str将会:

str = "04:00 PM"

回答by STO

At first, you need to convert time span to DateTime structure:

首先,您需要将时间跨度转换为 DateTime 结构:

var dt = new DateTime(2000, 12, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)

Then you need to convert the value to string with Short Timeformat

然后您需要将值转换为短时间格式的字符串

var result = dt.ToString("t"); // Convert to string using Short Time format

回答by Michal Klouda

You will need to get a DateTimeobject from your TimeSpanand then you can format it easily.

您需要DateTime从您的对象中获取一个对象TimeSpan,然后您可以轻松地对其进行格式化。

One possible solution is adding the timespan to any date with zero time value.

一种可能的解决方案是将时间跨度添加到任何具有零时间值的日期。

var timespan = new TimeSpan(3, 0, 0);
var output = new DateTime().Add(timespan).ToString("hh:mm tt");

The output value will be "03:00 AM"(for english locale).

输出值将是"03:00 AM"(对于英语语言环境)。

回答by Chris Marisic

Doing some piggybacking off existing answers here:

在此处借鉴现有答案:

public static string ToShortTimeSafe(this TimeSpan timeSpan)
{
    return new DateTime().Add(timeSpan).ToShortTimeString();
} 

public static string ToShortTimeSafe(this TimeSpan? timeSpan)
{
    return timeSpan == null ? string.Empty : timeSpan.Value.ToShortTimeSafe();
}

回答by Nandha kumar

Parse timespan to DateTime. For Example.    
//The time will be "8.30 AM" or "10.00 PM" or any time like this format.
    public TimeSpan GetTimeSpanValue(string displayValue) 
        {   
            DateTime dateTime = DateTime.Now;
                if (displayValue.StartsWith("10") || displayValue.StartsWith("11") || displayValue.StartsWith("12"))
                          dateTime = DateTime.ParseExact(displayValue, "hh:mm tt", CultureInfo.InvariantCulture);
                    else
                          dateTime = DateTime.ParseExact(displayValue, "h:mm tt", CultureInfo.InvariantCulture);
                    return dateTime.TimeOfDay;
                }

回答by Bilal

Very simple by using the string format

使用字符串格式非常简单

on .ToSTring("") :

.ToSTring("") :

  • if you use "hh" ->> The hour, using a 12-hour clock from 01 to 12.

  • if you use "HH" ->> The hour, using a 24-hour clock from 00 to 23.

  • if you add "tt" ->> The Am/Pm designator.

  • 如果使用 "hh" ->> 小时,使用从 01 到 12 的 12 小时制。

  • 如果使用 "HH" ->> 小时,使用从 00 到 23 的 24 小时制。

  • 如果添加“tt” ->> Am/Pm 指示符。

exemple converting from 23:12 to 11:12 Pm :

从 23:12 到 11:12 Pm 的示例:

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("hh:mm tt");   // this show  11:12 Pm
var res2 = d.ToString("HH:mm");  // this show  23:12

Console.WriteLine(res);
Console.WriteLine(res2);

Console.Read();

wait a second that is not all you need to care about something else is the system Culture because the same code executed on windows with other langage especialy with difrent culture langage will generate difrent result with the same code

稍等片刻,您需要关心的不仅仅是系统文化,因为在具有其他语言的 Windows 上执行的相同代码,尤其是具有不同文化语言的代码将使用相同的代码生成不同的结果

exemple of windows set to Arabic langage culture will show like that :

设置为阿拉伯语言文化的窗口示例将显示如下:

// 23:12 ?

// 23:12?

? means Evening (first leter of ????) .

? 意思是晚上(????的第一个字母)。

in another system culture depend on what is set on the windows regional and language option, it will show // 23:12 du.

在另一种系统文化中,取决于 Windows 区域和语言选项上的设置,它将显示 // 23:12 du。

you can change between different format on windows control panel under windows regional and language -> current format (combobox) and change... apply it do a rebuild (execute) of your app and watch what iam talking about.

您可以在 windows 区域和语言下的 windows 控制面板上的不同格式之间进行更改 -> 当前格式(组合框)并更改...应用它重新构建(执行)您的应用程序并观看我在说什么。

so who can I force showing Am and Pm Words in English event if the culture of the current system isn't set to English ?

那么,如果当前系统的文化未设置为英语,我可以强制在英语事件中显示 Am 和 Pm Words 吗?

easy just by adding two lines : ->

只需添加两行即可轻松:->

the first step add using System.Globalization;on top of your code

第一步添加using System.Globalization;在您的代码之上

and modifing the Previous code to be like this :

并将以前的代码修改为如下所示:

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.InvariantCulture); // this show  11:12 Pm

InvariantCulture => using default English Format.

InvariantCulture => 使用默认英文格式。

another question I want to have the pm to be in Arabic or specific language, even if I use windows set to English (or other language) regional format?

另一个问题 我想让 pm 使用阿拉伯语或特定语言,即使我使用设置为英语(或其他语言)区域格式的 windows?

Soution for Arabic Exemple :

阿拉伯语示例:

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.CreateSpecificCulture("ar-AE")); 

this will show // 23:12 ?

这将显示 // 23:12 ?

event if my system is set to an English region format. you can change "ar-AE" if you want to another language format. there is a list of each language and its format.

如果我的系统设置为英语区域格式,则事件。如果您想要另一种语言格式,您可以更改“ar-AE”。有每种语言及其格式的列表。

exemples : ar ar-SA Arabic ar-BH ar-BH Arabic (Bahrain) ar-DZ ar-DZ Arabic (Algeria) ar-EG ar-EG Arabic (Egypt)

示例: ar ar-SA 阿拉伯语 ar-BH ar-BH 阿拉伯语(巴林) ar-DZ ar-DZ 阿拉伯语(阿尔及利亚) ar-EG ar-EG 阿拉伯语(埃及)

回答by Ankit

You can try this:

你可以试试这个:

   string timeexample= string.Format("{0:hh:mm:ss tt}", DateTime.Now);

you can remove hh or mm or ss or tt according your need where hh is hour in 12 hr formate, mm is minutes,ss is seconds,and tt is AM/PM.

您可以根据需要删除 hh 或 mm 或 ss 或 tt,其中 hh 是 12 小时格式的小时,mm 是分钟,ss 是秒,tt 是 AM/PM。