Search code examples
c#.netasp.net-mvcdatetime-format

Convert string to string(datetime) in EST


I have string in "Sat, 20 Mar 2021 14:04:48 +0000" and I want to convert it as "20 Sat 2021 | 14:04 PM"

I want to convert the string as it is but it was appearing differently in my local and server.


Solution

  • First of all 20 Mar 2021 is Saturday, not Monday, let's correct it. Then you can ParseExact to get DateTime and finally represent it in the required format with a help of ToString():

      string source = "Sat, 20 Mar 2021 14:04:48 +0000";
    
      string result = DateTime
        .ParseExact(source, "ddd, dd MMM yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture)
        .ToUniversalTime()
        .ToString("dd MMM yyyy' | 'HH:mm tt", CultureInfo.InvariantCulture);
    

    Notes:

    • It seems that you want to obtain Universal (not Local) time, that's why I've added ToUniversalTime()
    • 14:04 PM looks strange for me (14:04 and 02:04 PM are much more frequent formats); put hh instead of HH to have 02:04 PM