简体   繁体   English

如何将特定字符串转换为 DateTime?

[英]How to convert a specific string to DateTime?

I have a string in this format:我有一个这种格式的字符串:

Tuesday, Sep 01, 2020 04:15
Thursday, Aug 27, 2020 03:56
Friday, Aug 28, 2020 07:30
Tuesday, Aug 04, 2020 08:00
[Route("/test")]
public async void TestParseTime()
{
    string pattern = "dddd, MMM dd, YYYY HH:MM";
    string newsTimeString = "Thursday, Aug 27, 2020 03:56";
    DateTime newsTime = DateTime.ParseExact(newsTimeString, pattern, null);
    Console.WriteLine("newsTime = " + newsTime);
}

But the parsing of the string to datetime fails with the following exception:但是将字符串解析为 datetime 失败,出现以下异常:

在此处输入图片说明

How to convert it to a DateTime in C#?如何将其转换为 C# 中的DateTime

I would suggest to use the powerfull Convert.ToDateTime method and simply feed the input in there:我建议使用强大的Convert.ToDateTime方法并简单地在那里输入输入:

string newsTimeString = "Thursday, Aug 27, 2020 03:56";
DateTime newsTime = Convert.ToDateTime(newsTimeString);
Console.WriteLine("newsTime = " + newsTime);

Output:输出:

newsTime = 27.08.2020 03:56:00新闻时间 = 27.08.2020 03:56:00

Actually the "Thursday" string is superfluous information for the DateTime object.实际上,“Thursday”字符串对于DateTime对象来说是多余的信息。 Because it will know the day of week from the calendar.因为它会从日历中知道星期几。 You can print it via the property:您可以通过属性打印它:

Console.WriteLine("Day = " + newsTime.DayOfWeek);

Output:输出:

Day = Thursday日 = 星期四

EDIT:编辑:

Apparently: "Convert.ToDateTime is just a call to DateTime.Parse " (comment by Panagiotis Kanavos) So in this case you can also use:显然:“Convert.ToDateTime 只是对 DateTime.Parse调用”(Panagiotis Kanavos 的评论)所以在这种情况下你也可以使用:

DateTime newsTime = DateTime.Parse(newsTimeString);

and get the same result, without specifying any format.并获得相同的结果,无需指定任何格式。

Disclaimer:免责声明:

From the Remarks section of the documentation :文档的备注部分:

"If value is not null, the return value is the result of invoking the "如果 value 不为 null,则返回值是调用
DateTime.Parse method on value using the formatting information in a DateTime.Parse 方法使用 a 中的格式信息对值进行处理
DateTimeFormatInfo object that is initialized for the current culture." -为当前区域性初始化的 DateTimeFormatInfo 对象。”-

Your pattern is incorrect.你的模式不正确。 patterns are case-sensitive.模式区分大小写。 Use this pattern instead:请改用此模式:

dddd, MMM dd, yyyy hh:mm dddd, MMM dd, yyyy hh:mm

string pattern = "dddd, MMM dd, yyyy hh:mm";
Console.WriteLine(DateTime.Now.ToString(pattern));

string newsTimeString = "Thursday, Aug 27, 2020 03:56";
DateTime newsTime = DateTime.ParseExact(newsTimeString, pattern, null);
Console.WriteLine("newsTime = " + newsTime);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM