Hi, I'm trying to split a string without separators into individual parts. It needs to be a date, but none of the date time operators I've tried are working.
Here's the string:20131105
And the method I normally use:
var birthDay = @currentMember.getProperty("birthday").Value; var birthDate = Convert.ToDateTime(birthDay);
I think it's because the string "20131105" isn't a valid format for the DateTime object.. I think you need to separate day, month, year with "-" or "." ortherwise it doesn't know which part is what..
This works:
string birthDay = "2013-11-05";
var birthDate = DateTime.Parse(birthDay);
<span>@birthDate.Day.ToString()</span>
This doesn't work:
string birthDay = "20131105";
var birthDate = DateTime.Parse(birthDay);
<span>@birthDate.Day.ToString()</span>
string birthDay = "20131105";
int year = int.Parse(birthDay.Substring(0, 4));
int month = int.Parse(birthDay.Substring(4, 2));
int day = int.Parse(birthDay.Substring(6, 2));
DateTime birthDate = new DateTime(year, month, day);
<span>@birthDate.ToShortDateString()</span>
or you could use other properties or methods of the DateTime object..
you just have to know at which positions the year, month, day in located and .. that the string here only contains numbers and are exactly on 8 characters..
e.g. if there only was 7 characters in the string, it would fails in the last Substring method for day as it can't take 2 more characters from position 6 if there only the 7 characters..
Split string without separators
Hi, I'm trying to split a string without separators into individual parts. It needs to be a date, but none of the date time operators I've tried are working.
Here's the string:20131105
And the method I normally use:
What am I missing here?
Hi Amir
I think it's because the string "20131105" isn't a valid format for the DateTime object.. I think you need to separate day, month, year with "-" or "." ortherwise it doesn't know which part is what..
This works:
This doesn't work:
/Bjarne
Hi Bjarne, how do you split a string without separators? I'm not creating the string so I don't have control over its initial format.
-Amir
You could do something like this:
or you could use other properties or methods of the DateTime object..
you just have to know at which positions the year, month, day in located and .. that the string here only contains numbers and are exactly on 8 characters..
e.g. if there only was 7 characters in the string, it would fails in the last Substring method for day as it can't take 2 more characters from position 6 if there only the 7 characters..
/Bjarne
Bjarne, the format of the string is very consistent so this worked great. Thank you!
-Amir
You can always use parseExact...
DateTime.ParseExact(birthDay, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
[http://www.dotnetperls.com/datetime-parse]
is working on a reply...