2

I have a field in a table with varchar data type which contains the time as 1800+0100, how can I show it like this 19:00 GMT? Is there any C# method which takes the time as 1800+0100 and converts to 19:00?

Thanks in advance. Any help would be greatly appreciated.

Rais Hussain
  • 203
  • 1
  • 2
  • 12

4 Answers4

5

If your time is actually in ISO-8601 format then you can do this:

DateTime dt = DateTime.ParseExact("1800+0100", "HHmmzzz", null,
                                  DateTimeStyles.AdjustToUniversal);
Console.WriteLine(dt.TimeOfDay);  // 17:00:00

But notice that this (correctly) outputs "17:00:00", not "19:00:00".

If your string isn't in ISO-8601 format -- and "1800+0100" really is meant to represent 19:00 GMT -- then you'll need to parse the string manually, or maybe pre-process it before passing it to ParseExact. Possibly something like this:

string s = "1800+0100";

string temp = s.Substring(0, 4) + ((s[4] == '+') ? '-' : '+') + s.Substring(5);
DateTime dt = DateTime.ParseExact(temp, "HHmmzzz", null,
                                  DateTimeStyles.AdjustToUniversal);
Console.WriteLine(dt.TimeOfDay);  // 19:00:00
LukeH
  • 263,068
  • 57
  • 365
  • 409
0

The DateTime class supports Add methods for DateTime objects. You can convert one time to another by adding any unit of time you desire.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
0

You can use DateTimeOffset for this. You begin by constructing an instance from a time and an offset, and then just fetch the UtcDateTime property.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
0

Beware though that UK only uses GMT (UniversalTime) in winter and summer time in summer.

mortb
  • 129
  • 1
  • 2