How can process a date that is in d/m/yyyy?

牧云@^-^@ 提交于 2019-12-06 10:04:57

Use the ParseExact method, and specify the format as M/d/yyyy (or d/M/yyyy, depending on what exactly you need):

var date = DateTime.ParseExact(input, "M/d/yyyy");

There is also an overload which can handle multiple date formats:

var date = DateTime.ParseExact(input, 
    new[] { "M/d/yyyy", "M-d-yyyy" }, 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.None);

This might still throw a FormatException if the input is in not in one of the allowed formats. To handle this a bit more safely, take a look at the TryParseExact method:

DateTime date;
var success = DateTime.TryParseExact(
    input, 
    new[] { "M/d/yyyy", "M-d-yyyy" }, 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.None, 
    out date);

Don't forget to specify the correct format / and invariant culture when you're converting the date back to a string:

var output = date.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!