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

时间:2012-10-24 07:28:01

标签: c# .net

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

System.TimeSpan storedTime = 03:00:00;

我可以将其重新存储在String类型的另一个变量中,如下所示吗?

String displayValue = "03:00 AM";

如果storedTime变量的值为

storedTime = 16:00:00;

然后它应该转换为:

String displayValue = "04:00 PM";

13 个答案:

答案 0 :(得分:153)

您可以通过将时间跨度添加到日期来完成此操作。

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"

答案 1 :(得分:14)

使用字符串格式非常简单

on .ToSTring("") :

  • 如果你使用“hh” - >>小时,从01到12使用12小时制。

  • 如果您使用“HH” - >>小时,使用00至23的24小时制。

  • 如果添加“tt” - >> Am / 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();

等待一秒,这不是你需要关心的其他东西是系统文化,因为在窗口上执行相同的代码与其他语言 特别是使用不同的文化语言将使用相同的代码生成不同的结果

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

// 23:12م

م表示晚上(مساء的第一个版本)。

在另一个系统文化中依赖于windows区域和语言选项上设置的内容,它将显示// 23:12 du。

你可以在windows区域和语言下的Windows控制面板上的不同格式之间切换 - >当前格式(组合框)和更改...应用它来重建(执行)您的应用程序,并观看我在谈论的内容。

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

只需添加两行即可: - >

第一步在代码顶部添加using System.Globalization;

并将Previous代码修改为:

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 =>使用默认的英文格式。

另一个问题我希望将pm设置为阿拉伯语或特定语言,即使我将Windows设置为英语(或其他语言)区域格式?

阿拉伯语例句:

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

这将显示// 23:12م

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

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

答案 2 :(得分:10)

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

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

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

04:00 PM

Standard Date and Time Format Strings

答案 3 :(得分:10)

string displayValue="03:00 AM";

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

你的基本设计或假设出了问题。

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

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

storeTime变量的值可以为
       storeTime=16:00:00;

不,它的值可以是4点,但表示是二进制的,TimeSpan不能记录16:004 pm之间的差异。

答案 4 :(得分:9)

在这里捎带现有答案:

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

答案 5 :(得分:6)

您需要从DateTime获取TimeSpan个对象,然后才能轻松对其进行格式化。

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

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

输出值为"03:00 AM"(英语语言环境)。

答案 6 :(得分:5)

您无法将 AM / PM 添加到TimeSpan。如果您想以12小时时钟格式显示时间,则无论如何都必须将TimaSpan值与DateTime相关联。

TimeSpan不适合使用12小时时钟格式,因为我们在这里讨论时间间隔

正如documentation;

中所述
  

TimeSpan对象表示时间间隔(持续时间或已用时间),以正数或负数天数,小时数,分钟,秒和分数秒。 TimeSpan结构也可用于表示一天中的时间,但前提是时间与特定日期无关。否则,应改为使用DateTimeDateTimeOffset结构。

同样Microsoft Docs描述如下;

  

TimeSpan值可以表示为[-]d.hh:mm:ss.ff,其中可选的减号表示负时间间隔,d组件为天,hh为小时在 24小时制上,mm为分钟,ss为秒,ff为几分之一。

因此,在这种情况下,您可以按如下方式使用AM / PM进行显示。

TimeSpan storedTime = new TimeSpan(03,00,00);
string displayValue = new DateTime().Add(storedTime).ToString("hh:mm tt");


旁注
另请注意,DateTime的{​​{3}}属性为TimeSpan,代表

  

时间间隔,表示自午夜以来经过的一天中的一小部分。

答案 7 :(得分:3)

将时间跨度解析为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");

str将是:

str = "04:00 PM"

答案 8 :(得分:2)

你可以试试这个:

public class WatchDir {

    protected HashSet<File> hashSetOfFiles;
    protected String filePath = "";

    public WatchDir() {

        chooseFilePath();
        if (filePath.isEmpty())
            return;

        listAnfangFiles();

        new Thread() {
            public void run() {
                listNewFiles();
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };
        }.start();
    }

    private void listNewFiles() {

        File file = new File(filePath);

        for (File f : file.listFiles()) {
            if (hashSetOfFiles.add(f)) {
                newFileFound(f);
            }
        }
    }

    private void newFileFound(File f) {

        // Hier kommen alle neuen Dateien an
        System.out.println(f.getName());
    }

    private void listAnfangFiles() {

        hashSetOfFiles = new HashSet<File>();
        File f = new File(filePath);

        for (File ff : f.listFiles()) {
            hashSetOfFiles.add(ff);
        }
    }

    private void chooseFilePath() {
        //
        // JFileChooser chooser = new JFileChooser();
        // chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        //
        // if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
        // filePath = chooser.getSelectedFile().getAbsolutePath();

        filePath = "C:\\Users\\maurice\\Desktop\\Test";
    }

    public static void main(String[] args) {
        new WatchDir();
    }
}

你可以根据需要删除hh或mm或ss或tt 哪里 hh是12小时甲酸盐的小时, mm是分钟,ss是秒,tt是AM / PM。

答案 9 :(得分:1)

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

答案 10 :(得分:0)

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

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

然后您需要将值转换为Short Time格式

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

答案 11 :(得分:0)

因为这种情况既烦人又很常见……我创建了一个帮助程序类,并在 NuGet 包中发布了该类。这可能是一个私有方法,可用于 MVC 视图以及后端 C# 代码。

public static string AsTimeOfDay(TimeSpan timeSpan, TimeSpanFormat timeSpanFormat = TimeSpanFormat.AmPm)
        {
            int hours = timeSpan.Hours;
            int minutes = timeSpan.Minutes;
            string AmOrPm = "AM";
            string returnValue = string.Empty;

            if (timeSpanFormat == TimeSpanFormat.AmPm)
            {
                if (hours >= 12)
                {
                    AmOrPm = "PM";
                }

                if (hours > 12)
                {
                    hours -= 12;
                }

                TimeSpan timeSpanAmPm = new TimeSpan(hours, minutes, 0);

                returnValue = timeSpanAmPm.ToString(@"h\:mm") + " " + AmOrPm;
            }
            else
            {
                returnValue = timeSpan.ToString(@"h\:mm");
            }

            return returnValue;
        }

enter image description here

答案 12 :(得分:0)

为避免时间跨度格式限制,请转换为日期时间。 最简单的表达是:

// Where value is a TimeSpan...
(new DateTime() + value).ToString("hh:mm tt");