C#中DateTime.ParseExact()怎么用
时间: 2024-03-25 07:37:57 浏览: 19
在C#中,`DateTime.ParseExact()`方法用于将指定格式的字符串表示形式转换为其等效的日期和时间。它的语法如下:
```c#
public static DateTime ParseExact(string s, string format, IFormatProvider provider);
```
其中,`s`参数是要转换的字符串,`format`参数是用于指定日期和时间格式的字符串,`provider`参数是一个可选的 `IFormatProvider` 对象,用于提供区域性特定的格式设置信息。
下面是一个使用`DateTime.ParseExact()`方法将字符串转换为`DateTime`类型的示例:
```c#
string dateStr = "2021-08-31 13:30:00";
string formatStr = "yyyy-MM-dd HH:mm:ss";
DateTime dt = DateTime.ParseExact(dateStr, formatStr, null);
```
在上面的示例中,我们使用`DateTime.ParseExact()`方法将字符串`dateStr`转换为`DateTime`类型。`formatStr`参数指定了输入字符串的格式,即年份、月份、日期、小时、分钟和秒数的顺序。我们还将`provider`参数设置为`null`,表示使用默认的区域性格式设置。
如果输入的字符串格式与指定的格式字符串不匹配,则会抛出一个`FormatException`异常。因此,在使用`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_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)