Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract DateTime from the string

Tags:

c#

I have a string below.

String s = "2014-12-19_16-09-19_test.10_A.txt";

what is the best way to extract the '2014-12-19_16-09-19' from the string rather then use String.Split()?

I have tried with regex but only extract '2014-12-19'.

(\d+)[-.\/](\d+)[-.\/](\d+)
like image 648
king jia Avatar asked Sep 11 '25 19:09

king jia


2 Answers

Use this regex:

Regex regex = new Regex(@"\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}");

Assumption: The string to be searched for is in the format "2014-12-19_16-09-19" only. If the separators are different, or if number of digits is variable, the regex has to be updated accordingly.

Alternatively, if the position of the underscores is always fixed, you could avoid regexes altogether. You can split by underscore and then join back the first and second elements of the split array, like so:

var v = s.Split('_');
Console.WriteLine(string.Join("_", new string[] {v[0],v[1]}));

Demo

like image 62
shree.pat18 Avatar answered Sep 14 '25 10:09

shree.pat18


I would use the following method:

const string format = "yyyy-MM-dd_HH-mm-ss";

String s = "2014-12-19_16-09-19_test.10_A.txt";

var dateTimeSubstring = s.Substring(0, format.Length);

var dt = DateTime.ParseExact(dateTimeSubstring, format, CultureInfo.CurrentCulture);

Console.WriteLine(dt);

With this code, you will get a 'dt' variable of type DateTime, with all functionality, like dt.Year, dt.Month, etc

like image 28
omikad Avatar answered Sep 14 '25 09:09

omikad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!