gpt4 book ai didi

c# - 如何验证 "date and time"字符串是否只有时间?

转载 作者:太空狗 更新时间:2023-10-29 20:51:58 27 4
gpt4 key购买 nike

我有一个字符串变量,用于存储可能是完整日期或部分日期的内容:

1) 全文日期:12/12/2010 12:33 AM

2) 部分日期:12:33 AM(没有日期字段只有时间)

我正在尝试找出解析字符串以确定字符串是否缺少日期字符串的最佳方法。原因是,在我的代码中,如果缺少日期,我会将默认日期附加到字符串(例如 1/1/1900)。请记住,时间可以采用多种格式。

更新 - 我对这个问题的特别回答。

正如所有“帖子”所说,这个问题有多种答案,这就是我最终使用的,希望它能帮助别人*:

public DateTime ProcessDateAndTime(string dateString)
{
string dateAndTimeString = dateString;

string[] timeFormats = new string[]
{
"hh:mm tt", "hh:mm:ss tt",
"h:mm tt", "h:mm:ss tt",
"HH:mm:ss", "HH:mm", "H:mm"
};
// check to see if the date string has a time only
DateTime dateTimeTemp;
if (DateTime.TryParseExact(dateString, timeFormats,
CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out dateTimeTemp))
{
// setting date to 01/01/1900
dateAndTimeString = new DateTime(1900, 1, 1).ToShortDateString() + " " + dateString;
}

return DateTime.Parse(dateAndTimeString);
}

*注意:此方法基于以下假设:您的应用程序中仅使用了特定数量的时间格式,并且保证传入格式正确的日期和时间或仅时间字符串(预清除垃圾文本的验证)。

最佳答案

使用

Convert.ToDateTime(字符串值,IFormatProviderProvider 提供者)

由于字符串有不同的风格,请根据需要提供不同的格式提供程序。

顺序可以是:

  • 仅限日期
  • 仅限时间
  • 日期时间

转换失败会抛出格式异常。如果您不想出现异常,请改用 Datetime.TryParse,因为它会返回一个 bool 值。

根据字符串的表示方式,您可以拥有 3 个以上的格式提供程序。

关于c# - 如何验证 "date and time"字符串是否只有时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7420399/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com