Reputation: 1552
how can I get the time difference from the string below, I want to get it with (-3.30)
[UTC - 3:30] Newfoundland Standard Time
and how to get null from the below string
[UTC] Western European Time, Greenwich Mean Time
and I want to get +3.30 in below string
[UTC + 3:30] Iran Standard Time
Upvotes: 2
Views: 1761
Reputation: 8116
Since you are just interested in the numbers, you could also use this.
String a = "[UTC - 3:30] Newfoundland Standard Time";
String b = "[UTC] Western European Time, Greenwich Mean Time";
String c = "[UTC + 3:30] Iran Standard Time";
Regex match = new Regex(@"(\+|\-) [0-9]?[0-9]:[0-9]{2}");
var matches = match.Match(a); // - 3:30
matches = match.Match(b); // Nothing
matches = match.Match(c); // + 3:30
Also supports +10 hour offsets.
Upvotes: 2
Reputation: 108790
You can extract the relevant part with:
Assert(input.StartsWith("[UTC",StringComparison.InvariantCultureIgnoreCase));
string s=input.Substring(4,input.IndexOf(']')-4).Replace(" ","");
And to get an offset in minutes from this string use:
if(s=="")s="0:00";
var parts=s.Split(':');
int hourPart=int.Parse(parts[0], CultureInfo.InvariantCulture);
int minutePart=int.Parse(parts[1], CultureInfo.InvariantCulture);
int totalMinutes= hourPart*60+minutePart*Math.Sign(hourPart);
return totalMinutes;
Upvotes: 2
Reputation: 57573
Try this:
public string GetDiff(string src)
{
int index = src.IndexOf(' ');
int lastindex = src.IndexOf(']');
if (index < 0 || index > lastindex) return null;
else return src.Substring(index + 1, lastindex - index -1 )
.Replace(" ", "").Replace(":", ".");
}
Upvotes: 0
Reputation: 3358
Regular expression:
\[UTC([\s-+0-9:]*)\]
The 1st group is - 3:30
. (with spaces)
var regex = new Regex(@"\[UTC([\s-+0-9:]*)\]");
var match = regex.Match(inputString);
string timediff;
if(match.Groups.Count > 0)
timediff = match.Groups[1].Value.Replace(" ", String.Empty); // if you don't want those spaces
else
// no timediff here
Upvotes: 5