Click here to Skip to main content
15,904,416 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
for example:"1995/3/4" to "1995/03/04"
I tried this code but I think it's better if there was an easier way
C#
string _date=:"1995/3/4"
string[] s=_date.Split('/');
_date=s[0]+"/"+Convert.toInt32(s[1]).ToString("00")+"/"+Convert.toInt32(s[2]).ToString("00");
Posted

You can use a regular expression for this.

First, add this at the top of your code file:
C#
using System.Text.RegularExpressions;

Then, use this code:
C#
_date = Regex.Replace(_date, @"/(?!\d{2,})", "/0");

This replaces every slash, that's not followed by 2 or more digits, with /0 (a slash and a zero).
 
Share this answer
 
Comments
mit62 3-Jul-14 6:23am    
thanks a lot
Thomas Daniels 3-Jul-14 6:25am    
You're welcome!
If these are always date strings, I would parse the date and then re-convert to a formatted string:
C#
//At the top:
using System.Globalization;
//
// Assuming this is Year/Month/Day in the format strings below.
// Adjustment for otherwise is pretty obvious.
string _date=:"1995/3/4";
DateTime rawDate;
if (DateTime.TryParseExact(_date, "yyyy/M/d", CultureInfo.InvariantCulture, DateTimeStyles.None, out rawDate))
{
  _date = rawDate.ToString(CultureInfo.InvariantCulture, "yyyy/MM/dd");
}
else
{
  // _date string was not a valid date. Handle "appropriately"
}

Use the appropriate CultureInfo for your application where I have CultureInfo.InvariantCulture above.
 
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