0

I have a situation in which user apply filter on reporedOn column data is filtered according to provided dates. But date is in below format which cause an exception.

Mon Jul 02 2018 00:00:00 GMT+0530 (India Standard Time)

I only want date and time. for ex. 8/29/2018 19:43:0 How can I convert above date format to the date time in C#. I am looking for general solution which works for any timezone. I don't want to add any patch in the code by checking length of the string and use substring function and extract the required string and all. Timezone may change from India Standard Time to Pacific Time or any other time zone.

sagar
  • 1
  • 2
  • You can try DateTime.ParseExact Method _https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=netframework-4.8_ `var date = DateTime.ParseExact( "Mon Jul 02 2018 00:00:00 GMT+0530 (India Standard Time)", "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(India Standard Time)'", CultureInfo.InvariantCulture);` – Bhushan Muttha Aug 12 '19 at 11:38
  • If user change the system time zone to PST then filter date change to: `Mon Aug 20 2018 09:49:00 GMT-0700 (Pacific Daylight Time)` – sagar Aug 12 '19 at 12:30

1 Answers1

1

I found the same solution as Bhushan in the comments did.

To convert the string

Mon Jul 02 2018 00:00:00 GMT+0530 (India Standard Time)

to a C# DateTime object you can use:

String str = "Mon Jul 02 2018 00:00:00 GMT+0530 (India Standard Time)";

DateTime dt= DateTime.ParseExact(str, "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(India Standard Time)'", CultureInfo.InvariantCulture);

If your string does not include (India Standard Time) then you can remove the format provider:

String str = "Mon Jul 02 2018 00:00:00 GMT+0530";

DateTime dt= DateTime.ParseExact(str, "ddd MMM dd yyyy HH:mm:ss 'GMT'K", null);

The 2 links I find useful for working with DateTime are number 1 which provides a good summary for the DateTime formatting and number 2 which provides a good explanation of converting between strings and DateTime in C#.

Hope this helps :)

Ben
  • 86
  • 2
  • If user change the system time zone to PST then filter date change to: `Mon Aug 20 2018 09:49:00 GMT-0700 (Pacific Daylight Time)` – sagar Aug 12 '19 at 12:27