0

I have a component in my c# application that provide strings like these:

"2004/1/11"

"2015/12/10"

"1998/1/2"

But i want to change them to these formats:

"2004/01/11"

"2015/12/10"

"1998/01/02"

Any idea?

1
  • no...component is used in all part of application and i just have to change output....i want to change output string to new format that i want
    – saeed
    Commented May 6, 2016 at 9:51

5 Answers 5

3

It seems that the strings in the question are actually dates, in that case DateTime class is what you're looking for:

  String source = "2015/12/10";
  String result = DateTime
   .ParseExact(source, "yyyy/M/d", CultureInfo.InvariantCulture)
   .ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);

In case the strings are not dates (say, some weird codes which look like dates) and you want just insert zeroes:

  String source = "2015/12/10"; 
  String result = Regex
    .Replace(source, "(?<=/)[0-9](?![0-9])", match => "0" + match.Value);
1

Try :

   string InputStr = "2004/1/11";
   String OutputStr = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(InputStr));
0
1

If you do not want to convert the strings to dates and back, you could use the Regex.Replace-method. The code could look a little something like this:

myString = Regex.Replace(myString,@"[^\d](\d)(?=(/|$))","/0$1");

EDIT: Corrected the pattern.

1
  • Counter example: myString = "2015/12/1";; the output is 2015/012/01 when 2015/12/01 expected Commented May 6, 2016 at 10:05
0

This might help you out with your question: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Maybe a timeformat setting will solve your problem.

0

its date so you can convert it this way

string str = "2004/1/11";
DateTime dt = DateTime.ParseExact(str, "yyyy/M/dd", CultureInfo.InvariantCulture);
string newstr = dt.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture)
2
  • Do not omit CultureInfo.InvariantCulture in the .ToString() or you can have, say, 2004.01.11 (notice dots) since current culture will be used - Russian in the output above Commented May 6, 2016 at 10:03
  • when parsing exact "yyyy/M/d" (please, notice one d only) is a better pattern than "yyyy/M/dd" in a view of "1998/1/2" input which will throw a format exception. Commented May 6, 2016 at 10:07

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.