简体   繁体   中英

How to convert informal string value to Date time in c#

All of my friend. I want to convert informal string to dateTime in c#. Here my string value is "01042016" .How can convert? can i need another step to change DateTime .

This is my code:

string FinancialYear = "01042016-31032017";
string[] splitDate = FinancialYear.Split('-');
DateTime startDate = Convert.ToDateTime(splitDate[0].ToString(),"dd/MM/yyyy"));

As we can see that the input date will be in the format ddMMyyyy so here the best option for converting the input to DateTime object is DateTime.TryParseExact the code for this will be :

string FinancialYear = "01042016-31032017";
string[] splitDate = FinancialYear.Split('-');
DateTime startDate ;
if(DateTime.TryParseExact(splitDate[0],"ddMMyyyy",CultureInfo.InvariantCulture,DateTimeStyles.None,out startDate))
{
    // Proceed with the startDate it will have the required date
}
else
     // Show failure message      

This will create an Enumerable where index 0 is the first date and index 1 is the second date.

string FinancialYear = "01042016-31032017";
var dateRange = FinancialYear.Split('-')
    .Select(d => DateTime.ParseExact(d, "ddMMyyyy", CultureInfo.InvariantCulture);

If you are not sure of the format your best bet is using DateTime.Parse() or DateTime.TryParse()

You are not 100% guaranteed that the date will be parsed correctly, especially in cases where the day and month numbers could be in the wrong order.

It is best to specify a required date format if you can so you can be sure the date was parsed correctly.

if you string is in static format, you can convert it by reconvert it to valid string format first such as

string validstring = splitDate[0].ToString().Substring(4,4)+"-"+splitDate[0].ToString().Substring(2,2) +"-"+ splitDate[0].ToString().Substring(0,2);
DateTime startDate = Convert.ToDateTime(validstring,"dd/MM/yyyy"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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