简体   繁体   English

如何将 Paypal 的 HH:MM:SS DD Mmm(.) YYYY PST/PDT 转换为 C# UTC 日期时间?

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

I would like to log a payment_date in this format in a SQL Server database.我想在 SQL 服务器数据库中以这种格式记录 payment_date。

Update.更新。 Instinct was right on this one.本能在这一点上是对的。 Found a solution here: http://www.codeillustrator.com/2010/03/converting-paypal-paymentdate-to-net.html , verifying... of course, if Paypal ever moves out of the West Coast, I'll be in trouble. Found a solution here: http://www.codeillustrator.com/2010/03/converting-paypal-paymentdate-to-net.html , verifying... of course, if Paypal ever moves out of the West Coast, I'会有麻烦的。 Is there a better way to parse this?有没有更好的方法来解析这个? Maybe with TimeZone?也许与时区?

public static DateTime ConvertPayPalDateTime(string payPalDateTime)
{
    // accept a few different date formats because of PST/PDT timezone and slight month difference in sandbox vs. prod.
    string[] dateFormats = { "HH:mm:ss MMM dd, yyyy PST", "HH:mm:ss MMM. dd, yyyy PST", "HH:mm:ss MMM dd, yyyy PDT", "HH:mm:ss MMM. dd, yyyy PDT" };
    DateTime outputDateTime;

    DateTime.TryParseExact(payPalDateTime, dateFormats, new CultureInfo("en-US"), DateTimeStyles.None, out outputDateTime);

    // convert to local timezone
    outputDateTime = outputDateTime.AddHours(3);

    return outputDateTime;
}

Wait a sec, that code above is completely wrong for me.等一下,上面的代码对我来说是完全错误的。 I'm on the West Coast.我在西海岸。 Ideally this should be updated to send the date to a proper UTC DateTime and handle any time zone.理想情况下,这应该更新以将日期发送到适当的 UTC DateTime 并处理任何时区。 Also the code above doesn't handle PDT properly (if converted to UTC).上面的代码也不能正确处理 PDT(如果转换为 UTC)。

Update2.更新2。 Apparently, at least in previous versions, the sandbox would return "Feb."显然,至少在以前的版本中,沙盒会返回“Feb”。 while the live returns "Feb".而现场返回“二月”。 Lol.哈哈。 Someone save me!有人救我!

Update3.更新3。 Link to Regex version http://www.ifinity.com.au/Blog/EntryId/77/Converting-PayPal-Dates-to-Net-DateTime-using-Regex , but debugging could be an issue.链接到正则表达式版本http://www.ifinity.com.au/Blog/EntryId/77/Converting-PayPal-Dates-to-Net-DateTime-using-Regex ,但调试可能是一个问题。 Regex does not seem like the right way to do this.正则表达式似乎不是正确的方法。 There must be a better way.一定会有更好的办法。

/// <summary>
/// Converts a PayPal datestring into a valid .net datetime value
/// </summary>
/// <param name="dateValue">a string containing a PayPal date</param>
/// <param name="localUtcOffset">the number of hours from UTC/GMT the local 
/// time is (ie, the timezone where the computer is)</param>
/// <returns>Valid DateTime value if successful, DateTime.MinDate if not</returns>
private static DateTime ConvertFromPayPalDate(string rawPayPalDate, int localUtcOffset)
{
    /* regex pattern splits paypal date into
     * time : hh:mm:ss
     * date : Mmm dd yyyy
     * timezone : PST/PDT
     */
     const string payPalDateRegex = @"(?<time>\d{1,2}:\d{2}:\d{2})\s(?<date>(?<
Mmm>[A-Za-z\.]{3,5})\s(?<dd>\d{1,2}),?\s(?<yyyy>\d{4}))\s(?<tz>[A-Z]{0,3})";  
    //!important : above line broken over two lines for formatting - rejoin in code editor
    //example 05:49:56 Oct. 18, 2009 PDT
    //        20:48:22 Dec 25, 2009 PST
    Match dateMatch = Regex.Match(rawPayPalDate, payPalDateRegex, RegexOptions.IgnoreCase);
    DateTime time, date = DateTime.MinValue;
    //check to see if the regex pattern matched the supplied string
    if (dateMatch.Success)
    {
        //extract the relevant parts of the date from regex match groups
        string rawDate = dateMatch.Groups["date"].Value;
        string rawTime = dateMatch.Groups["time"].Value;
        string tz = dateMatch.Groups["tz"].Value;

        //create date and time values
        if (DateTime.TryParse(rawTime, out time) && DateTime.TryParse(rawDate, out date))
        {
            //add the time to the date value to get the datetime value
            date = date.Add(new TimeSpan(time.Hour, time.Minute, time.Second));
            //adjust for the pdt timezone.  Pass 0 to localUtcOffset to get UTC/GMT
            int offset = localUtcOffset + 7; //pdt = utc-7, pst = utc-8
            if (tz == "PDT")//pacific daylight time
                date = date.AddHours(offset);
            else  //pacific standard time
                date = date.AddHours(offset + 1);
        }
    }
    return date;
}

I haven't done any C# since 2006, so this code probably doesn't compile.自 2006 年以来,我没有做过任何 C#,所以这段代码可能无法编译。 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);
}

This should work这应该工作

 public static DateTime ConvertPayPalDateTime(string payPalDateTime)
 { 
    CultureInfo enUS = new CultureInfo("en-US");
    // accept a few different date formats because of PST/PDT timezone and slight month difference in sandbox vs. prod.
    string[] dateFormats = { "HH:mm:ss MMM dd, yyyy PST", "HH:mm:ss MMM. dd, yyyy PST", "HH:mm:ss MMM dd, yyyy PDT", "HH:mm:ss MMM. dd, yyyy PDT",
                             "HH:mm:ss dd MMM yyyy PST", "HH:mm:ss dd MMM. yyyy PST", "HH:mm:ss dd MMM yyyy PDT", "HH:mm:ss dd MMM. yyyy PDT"};
    DateTime outputDateTime;

    DateTime.TryParseExact(payPalDateTime, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out outputDateTime);

    // convert to local timezone
    TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");

    outputDateTime = TimeZoneInfo.ConvertTime(outputDateTime, hwZone, TimeZoneInfo.Local);

    return outputDateTime;
}

The code in this post seems to work fine: http://www.codeillustrator.com/2010/03/converting-paypal-paymentdate-to-net.html这篇文章中的代码似乎工作正常: http://www.codeillustrator.com/2010/03/converting-paypal-paymentdate-to-net.html

using System;
using System.Globalization;

public static class PayPalTransaction
{
    public static DateTime ConvertPayPalDateTime(string payPalDateTime)
    {
    // accept a few different date formats because of PST/PDT timezone and slight month difference in sandbox vs. prod.
        string[] dateFormats = { "HH:mm:ss MMM dd, yyyy PST", "HH:mm:ss MMM. dd, yyyy PST", "HH:mm:ss MMM dd, yyyy PDT", "HH:mm:ss MMM. dd, yyyy PDT" };
        DateTime outputDateTime;

        DateTime.TryParseExact(payPalDateTime, dateFormats, new CultureInfo("en-US"), DateTimeStyles.None, out outputDateTime);

        // convert to local timezone
        outputDateTime = outputDateTime.AddHours(3);

        return outputDateTime;
    }
}

(answer cross-posted for this similar question: How to cast this date and save to database ) (回答这个类似问题的交叉发布: 如何投射这个日期并保存到数据库

Assuming you have already parsed the date with DateTime.ParseExact() (or one of the other similar methods) you can call DateTime.ToUniversalTime()假设您已经使用DateTime.ParseExact() (或其他类似方法之一)解析了日期,您可以调用DateTime.ToUniversalTime()

EDIT: perhaps TimeZoneInfo.ConvertTimeToUtc is more appropriate: The ToUniversalTime method converts a DateTime value from local time to UTC.编辑:也许 TimeZoneInfo.ConvertTimeToUtc 更合适: ToUniversalTime 方法将 DateTime 值从本地时间转换为 UTC。 To convert the time in a non-local time zone to UTC, use the TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) method.要将非本地时区的时间转换为 UTC,请使用 TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) 方法。 To convert a time whose offset from UTC is known, use the ToUniversalTime method.要转换与 UTC 的偏移量已知的时间,请使用 ToUniversalTime 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将字符串“dd.MM.yyyy HH:mm:ss.mmm”转换为 c# 中的日期时间 - how to convert string “dd.MM.yyyy HH:mm:ss.mmm” to the datetime in c# 如何将C#中的DateTime.now转换为yyyy-mm-dd hh:mm:ss.sssssss? - How I can convert DateTime.now in C# to yyyy-mm-dd hh:mm:ss.sssssss? C#将字符串“yyyy-MM-dd hh:mm:ss &#39;UTC&#39;”转换为日期时间 - C# Convert a string "yyyy-MM-dd hh:mm:ss 'UTC'" to date time 如何在 C# 中将“YYYY-MM-DDThh:mmTZD”转换为 yyyy-MM-dd hh:mm:ss - How to convert “YYYY-MM-DDThh:mmTZD” to yyyy-MM-dd hh:mm:ss in C# 将字符串转换为日期时间,格式为 yyyy-MM-dd HH:mm:ss in C# - convert string to datetime with form yyyy-MM-dd HH:mm:ss in C# 将dd / MM / yyyy hh:mm:ss.fff从String转换为C#中的DateTime - Convert dd/MM/yyyy hh:mm:ss.fff from String to DateTime in C# 在 c# LINQ 中比较日期时间“MM/dd/yyyy hh:mm:ss”和“yyyy-MM-dd hh:mm:ss” - Compare dateTime "MM/dd/yyyy hh:mm:ss" with "yyyy-MM-dd hh:mm:ss" in c# LINQ 如何通过linq将MM / dd / YYYY hh:mm:ss AM转换为YYYY-MM-dd datetime格式? - how to convert MM/dd/YYYY hh:mm:ss AM to YYYY-MM-dd datetime format by linq? C#DateTime从yyyy-MM-ddTHH转换:mm:ss到dd MMM yyyy - C# DateTime Conversion from yyyy-MM-ddTHH:mm:ss to dd MMM yyyy 将字符串转换为日期时间dd / MM / yyyy hh:mm:ss tt - Convert string to Datetime dd/MM/yyyy hh:mm:ss tt
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM