c# - 带有 TryParseExact 的 FormatException

标签 c# datetime format

我想将输入的时间格式化为特定标准:

private String CheckTime(String value)
{
    String[] formats = { "HH mm", "HHmm", "HH:mm", "H mm", "Hmm", "H:mm", "H" };
    DateTime expexteddate;
    if (DateTime.TryParseExact(value, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out expexteddate))
       return expexteddate.ToString("HH:mm");
    else
       throw new Exception(String.Format("Not valid time inserted, enter time like: {0}HHmm", Environment.NewLine));
}

当用户输入时:“09 00”、“0900”、“09:00”、“9 00”、“9:00”
但是当用户输入类似:"900""9" 时,系统无法格式化它,为什么? 它们是我接受的默认格式。

string str = CheckTime("09:00"); // works
str = CheckTime("900");          // FormatException at TryParseExact

最佳答案

Hmm 匹配“0900”,H 匹配“09”,你必须给出 2 个数字。

你可以这样改变用户输入:

private String CheckTime(String value)
{
    // change user input into valid format
    if(System.Text.RegularExpressions.Regex.IsMatch(value, "(^\\d$)|(^\\d{3}$)"))
        value = "0"+value;

    String[] formats = { "HH mm", "HHmm", "HH:mm", "H mm", "Hmm", "H:mm", "H" };
    DateTime expexteddate;
    if (DateTime.TryParseExact(value, formats, System.Globalization.CultureInfo.InvariantCulture,     System.Globalization.DateTimeStyles.None, out expexteddate))
       return expexteddate.ToString("HH:mm");
    else
       throw new Exception(String.Format("Not valid time inserted, enter time like:     {0}HHmm", Environment.NewLine));
}

关于c# - 带有 TryParseExact 的 FormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24057063/

相关文章:

c# - 从 WebAPI 调用返回 Sitecore 媒体项目

c# - Entity Framework 查询过滤器实现以获得最佳性能

c# - 大量物体的碰撞检测

Perl Time::Piece 如果格式不正确则使用当前日期

vb.net - 在vb.net中将字符串转换为datetime

arrays - 轻松将xml中的字符串更改为xml中的数组

c# - 避免 MsiExec 卸载中的确认框

Mysql日期和时差

java - 如何使用 IReport 以法语格式显示日期

iphone - 我想要 iLBC 格式,但似乎只能录制 IMA4 格式的音频