开发者

how to split the string to get date only

开发者 https://www.devze.com 2023-04-12 08:40 出处:网络
I have got thestring like this below.... string a = backup-2011-10-12_17-16-51.zip How can i split the above string so thatonly getthis part 2011-10-12

I have got the string like this below....

 string a = backup-2011-10-12_17-16-51.zip

How can i split the above string so that only get this part 2011-10-12

For that I 开发者_高级运维have tried this below but i am not sure how to split the string exact like this

2011-10-12

  string[] getfiledate = a.Split(new[] { '.', '-','_' });

would any one pls help on how to split the one string .. .....

many thanks in advance..


If the string is always the same length, just use

a.Substring(7,10)


A regex would be beneficial here.

(\d{4}-\d{2}-\d{2})


Here's my personal favorite:

DateTime dt = DateTime.ParseExact("backup-2011-10-12_17-16-51.ip", "backup-yyyy-dd-MM_HH-mm-ss.ip", null);

This avoids substring calculations, but if you'll notice I had to remove the z from zip in your example because in timezone calculation z is the gmt offset... if you can avoid the z, then this works very nicely.

EDIT For a more awesome answer

use @ and \ to escape the z:

DateTime dt = DateTime.ParseExact("backup-2011-10-12_17-16-51.zip", @"backup-yyyy-dd-MM_HH-mm-ss.\zip", null);


If you can expect that exact format all the time this will work

 string a = "backup-2011-10-12_17-16-51.zip";
 var temp = a.Replace("backup-", String.Empty);
 temp = temp.Substring(0, temp.IndexOf('_'));


Very quick and dirty

string a = "backup-2011-10-12_17-16-51.zip";
string g = a.Replace("backup-", string.Empty);
string k = g.Remove(g.IndexOf("_"));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号