C# 判断字符串是否属于时间
时间: 2023-10-31 09:09:13 浏览: 49
可以使用C#的DateTime.TryParseExact方法来判断字符串是否属于时间。该方法可以将字符串转换为DateTime类型,如果转换成功则说明该字符串是时间格式。
下面是一个示例代码:
```
string input = "2021-01-01 12:00:00";
DateTime date;
if (DateTime.TryParseExact(input, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
Console.WriteLine("该字符串是时间格式,转换结果为:" + date);
}
else
{
Console.WriteLine("该字符串不是时间格式");
}
```
该代码将输入的字符串按照指定的格式进行转换,如果转换成功,则说明该字符串是时间格式。如果转换失败,则说明该字符串不是时间格式。
相关问题
c# 时间字符串跟当前时间对比
要比较一个 C# 时间字符串与当前时间,可以使用以下代码:
```csharp
string timeString = "2022-01-01 12:00:00";
DateTime dateTime = DateTime.ParseExact(timeString, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
TimeSpan timeDifference = dateTime - DateTime.Now;
if (timeDifference.TotalSeconds > 0)
{
Console.WriteLine("时间字符串比当前时间晚");
}
else if (timeDifference.TotalSeconds < 0)
{
Console.WriteLine("时间字符串比当前时间早");
}
else
{
Console.WriteLine("时间字符串和当前时间相同");
}
```
首先,我们将时间字符串转换为 `DateTime` 对象。这里使用 `ParseExact` 方法指定时间字符串的格式,避免因为不同的本地化设置而导致解析错误。
然后,我们计算时间差,并根据时间差的正负来判断时间字符串是比当前时间早还是晚。如果时间差为零,则说明时间字符串和当前时间相同。
C# 时间字符串跟当前时间对比
要比较一个 C# 时间字符串与当前时间,可以使用以下代码:
```csharp
string timeString = "2022-01-01 12:00:00";
DateTime dateTime = DateTime.ParseExact(timeString, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
TimeSpan timeDifference = dateTime - DateTime.Now;
if (timeDifference.TotalSeconds > 0)
{
Console.WriteLine("时间字符串比当前时间晚");
}
else if (timeDifference.TotalSeconds < 0)
{
Console.WriteLine("时间字符串比当前时间早");
}
else
{
Console.WriteLine("时间字符串和当前时间相同");
}
```
首先,我们将时间字符串转换为 `DateTime` 对象。这里使用 `ParseExact` 方法指定时间字符串的格式,避免因为不同的本地化设置而导致解析错误。
然后,我们计算时间差,并根据时间差的正负来判断时间字符串是比当前时间早还是晚。如果时间差为零,则说明时间字符串和当前时间相同。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)