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?
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?
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);
Try :
string InputStr = "2004/1/11";
String OutputStr = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(InputStr));
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.
myString = "2015/12/1";
; the output is 2015/012/01
when 2015/12/01
expected
Commented
May 6, 2016 at 10:05
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.
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)
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
"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