-2

I am receiving the API responses and doing some logic.

I am trying to convert a string to DateTime but I am unable to convert it in C#. I tried multiple ways but I am getting string in invalid format.

I need to convert "EEE MMM d HH:mm:ss z yyyy" to an equivalent DateTime format in C#.

I have two dates as below and need to calculate the total days from the two dates

var dt1="Wed Jul 14 07:59:30 BST 2021"; var dt2="Fri Jul 16 08:59:30 BST 2021";

Please give me any suggestions.

  • 1
    Welcome on SO For your next question, please use the search function. There are already many questions like this on SO. Also provide a small snippet of your current code. Furthermore, [the official documentation](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parse?view=net-5.0) is very exhaustive when it comes to parsing – mu88 Sep 20 '21 at 11:20
  • There is no built-in way to parse the time zone when written like that. Are your dates always "BST", or could the dates contain other time zones? – Matthew Watson Sep 20 '21 at 11:26
  • 1
    Does this answer your question? [Parse DateTime with time zone of form PST/CEST/UTC/etc](https://stackoverflow.com/questions/241789/parse-datetime-with-time-zone-of-form-pst-cest-utc-etc) – Fildor Sep 20 '21 at 11:26
  • If you have any say in what that API provides, ask for either Offset instead of TimeZone if it has to be human readable or something like Unix Timestamp if not. – Fildor Sep 20 '21 at 11:32
  • Hi Matthew , I am getting BST and GMT as of now. I will get any format in the future. It could be helpful if share some custom method to convert it to equivalent DateTime format. – pughazendhi C Sep 20 '21 at 11:57

1 Answers1

2

Here is what you need:

using System;
using System.Globalization;
public class Program
{
    public static void Main()
    {
        String yourDate = "Wed Jul 14 07:59:30 BST 2021";
        DateTime dt = DateTime.ParseExact( yourDate,"ddd MMM dd HH:mm:ss 'BST' yyyy", CultureInfo.InvariantCulture);
        Console.WriteLine(dt.ToString());
    }
}

It will give you this output: 7/14/2021 7:59:30 AM

MegaMinx
  • 109
  • 7