How do I convert Paypal's HH:MM:SS DD Mmm(.) YYYY PST/PDT to a C# UTC DateTime?

后端 未结 4 442
南旧
南旧 2021-01-12 01:28

I would like to log a payment_date in this format in a SQL Server database.

Update. Instinct was right on this one. Found a solution here: http://w

4条回答
  •  温柔的废话
    2021-01-12 02:00

    I haven't done any C# since 2006, so this code probably doesn't compile. Test it before you fly!

    public static DateTime ConvertPayPalDateTime(string payPalDateTime)
    {
      // Get the offset.
      // If C# supports switching on strings, it's probably more sensible to do that.
      int offset;
      if (payPalDateTime.EndsWith(" PDT"))
      {
         offset = 7;
      }
      else if (payPalDateTime.EndsWith(" PST"))
      {
         offset = 8;
      }
      else
      {
        throw some exception;
      }
    
      // We've "parsed" the time zone, so remove it from the string.
      payPalDatetime = payPalDateTime.Substring(0,payPalDateTime.Length-4);
    
      // Same formats as above, but with PST/PDT removed.
      string[] dateFormats = { "HH:mm:ss MMM dd, yyyy", "HH:mm:ss MMM. dd, yyyy" };
    
      // Parse the date. Throw an exception if it fails.
      DateTime ret = DateTime.ParseExact(payPalDateTime, dateFormats, new CultureInfo("en-US"), DateTimeStyles.None, out outputDateTime);
    
      // Add the offset, and make it a universal time.
      return ret.AddHours(offset).SpecifyKind(DateTimeKind.Universal);
    }
    

提交回复
热议问题