dd hh:mm 格式字符串转 DateTime
时间: 2024-04-24 12:23:54 浏览: 15
要将形如 "dd hh:mm" 的字符串转换为 `DateTime` 对象,你可以使用 `DateTime.ParseExact` 或 `DateTime.TryParseExact` 方法,并指定自定义的日期时间格式。以下是示例代码:
```csharp
string dateString = "20 10:30";
DateTime dateTime;
// 使用 DateTime.ParseExact 进行转换
dateTime = DateTime.ParseExact(dateString, "dd HH:mm", CultureInfo.InvariantCulture);
// 使用 DateTime.TryParseExact 进行转换
bool success = DateTime.TryParseExact(dateString, "dd HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
if (success)
{
// 转换成功,可以使用 dateTime 对象进行操作
Console.WriteLine(dateTime);
}
else
{
// 转换失败,处理错误逻辑
Console.WriteLine("无效的日期时间格式");
}
```
在上述代码中,我们使用了自定义的日期时间格式字符串 `"dd HH:mm"` 来指定日期的格式。`dd` 表示两位数的日期,`HH` 表示两位数的小时,`mm` 表示两位数的分钟。请根据实际的日期时间格式进行相应的调整。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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_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)
![](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)