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

2019-05-23 03:04发布

I have to process dates . If the format i specify is mm/dd/yyyy and the date is like 7/5/2013, it is throwing a format exception. Does the date has to be like 07/05/2013? If yes how can i change the date from 7/5/2013 to 07/05/2013 programatically ? and the date format is not specific. I can have dates in mm-dd-yyyy or yyyy-mm-dd and the dates can come like 7-5-2013.

1条回答
迷人小祖宗
2楼-- · 2019-05-23 03:37

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);
查看更多
登录 后发表回答