Click here to Skip to main content
15,911,646 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how to format an string value 10072017 to 10/07/2017

What I have tried:

how to format an string value 10072017 to 10/07/2017
Posted
Updated 4-Jul-17 1:46am

// I'm assuming that 10/07 is 10th July.  If it is 7th Oct then swap the dd and MM in
// the code below
string a = "10072017";

DateTime dt;
DateTime.TryParseExact(a, "ddMMyyyy", System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out dt);

string b = dt.ToString("dd/MM/yyyy");
 
Share this answer
 
Comments
Member 12857358 4-Jul-17 7:32am    
Thanks alot. its working perfectly
You could cheat:
string input = "10072017";
string formatted = input.Substring(0, 2) + "/" + input.Substring(2, 2) + "/" + input.Substring(4);
But a better solution would be to convert it to a DateTime:
string input = "10072017";
DateTime dt;
if (!DateTime.TryParseExact(input, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
    {
    // Report problem to user - bad date.
    ...
    return;
    }
string formatted = dt.ToString("dd/MM/yyyy");
 
Share this answer
 
If you have the initial value in the initial then
string result=initial.Substring(0,2)+"/"+initial.Subsring(2,2)+"/"+initial.Substring(4,4)
or
string function format(string initial){<br />
   return initial.Substring(0,2)+"/"+initial.Subsring(2,2)+"/"+initial.Substring(4,4)<br />
}<br />
 
Share this answer
 
//Assuming date in dd-mm-yyyy format
string str = "10072017";  
int day = Convert.ToInt32(str.Substring(0,2));
int month = Convert.ToInt32(str.Substring(2, 2));
int year = Convert.ToInt32(str.Substring(4, 4));
DateTime dt = new DateTime(year, month, day);            
Console.WriteLine("{0:dd/MM/yyyy}", dt);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900