Reputation: 1754
I have a date stamp (020920111422) and I want to split it to
day = 02, month = 09, year = 2011, hour = 14, and minute = 22
Is there a "split string at position" method in C#?
Upvotes: 9
Views: 11892
Reputation: 2033
For more usecase, maybe this can help
string rawData = "LOAD:DETAIL 11.00.0023.02.201614:52:00NGD ...";
var idx = 0;
Func<int, string> read = count =>
{
var result = rawData.Substring(idx, count);//.Trim();
idx += count;
return result;
};
var type = read(16);
var version = read(8);
var date = read(18);
var site = read(8);
//...
Upvotes: 0
Reputation: 11844
Instead you can convert the date stamp by using Datatime.ParseExact
and can extract the day, month, year, hour and minute you want from that date stamp. Refer the following code part for Datetime.ParseExact
converting.
DateTime.ParseExact(YourDate, "ddMMyyyyHHmm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
Upvotes: 2
Reputation: 273581
You could also use
var d = DateTime.Parse(s, "ddMMyyyyHHmm");
if the end-goal is a DateTime.
Upvotes: 3
Reputation: 62544
Answering on question considering "split string at position" - you can leverage String.Substring(Int32, Int32) method by calling multiple times with different offsets.
Also take a look at LINQ Take() and Skip() methods which allows provide count of elements to return as well.
Otherwise see examples which other guys are provided using DateTime.ParseExact(),
I believe this is most correct way to convert string you've provided to DateTime
value.
Upvotes: 3
Reputation: 70379
you can do this via SubString
- for example:
string myDay = mydatestamp.SubString (0,2);
OR create a DateTime:
DateTime myDateTime = DateTime.ParseExact ( mydatestamp, "ddMMyyyyHHmm" , CultureInfo.InvariantCulture );
Upvotes: 7
Reputation: 1063774
You want:
string x = s.Substring(0, i), y = s.Substring(i);
(or maybe i-1/i+1 depending on your exact requirements).
However, you could also use DateTime.ParseExact
to load it into a DateTime
by telling it the explicit format:
var when = DateTime.ParseExact("020920111422", "ddMMyyyyHHmm",
CultureInfo.InvariantCulture);
Upvotes: 19