我如何把PayPal的HH:MM:(。)SS DD嗯YYYY PST / PDT到C#UTC日期时间? [英] How do I convert Paypal's HH:MM:SS DD Mmm(.) YYYY PST/PDT to a C# UTC DateTime?

查看:208
本文介绍了我如何把PayPal的HH:MM:(。)SS DD嗯YYYY PST / PDT到C#UTC日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想记录以这种格式在SQL Server数据库PAYMENT_DATE。



更新。直觉是正确的就这一个。这里找到一个解决方案: http://www.codeillustrator.com/2010/03 /converting-paypal-paymentdate-to-net.html ,当然核实......,如果贝宝曾经移出西海岸,我就惨了。有没有更好的方法来分析呢?也许与时区?



 公共静态的DateTime ConvertPayPalDateTime(字符串payPalDateTime)
{
//接受几不同的日期格式,因为PST / PDT时区和沙箱与督促略有差异一个月的。
的String []的D​​ateFormats = {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,新的CultureInfo(EN-US),DateTimeStyles.None,出outputDateTime);

//转换为本地时区
outputDateTime = outputDateTime.AddHours(3);

返回outputDateTime;
}



等一下,那上面的代码是完全错误的我。我在西海岸!理论上讲,该应更新日期发送给正确的UTC日期时间以及处理任何时区。此外上面的代码不处理PDT正确(如果转换为UTC)。



UPDATE2。显然,至少在以前的版本中,沙盒将返回二月而现场返回二月。大声笑。有人救我!



UPDATE3。链接的正则表达式版本的http://www.ifinity.com.au/Blog/EntryId/77/Converting-PayPal-Dates-to-Net-日期时间,使用正则表达式,但调试可能是一个问题。正则表达式似乎并不喜欢这样做的正确方法。必须有一个更好的办法

  ///<总结> 
///一个PayPal datestring为有效的.NET datetime值
///<转换; /总结>
///< PARAM NAME =DATEVALUE获得包含一个PayPal日期℃的字符串; /参数>
///< PARAM NAME =localUtcOffset>将与UTC / GMT的小时数在本地
///时间(即,时区所在的计算机)和LT; /参数> ;
///<退货和GT;有效的datetime值,如果成功,DateTime.MinDate如果不是< /回报>
私有静态的DateTime ConvertFromPayPalDate(字符串rawPayPalDate,诠释localUtcOffset)
{
/ *正则表达式拆分贝宝日起
*时间:HH:MM:SS
*日期:嗯月日年
*的时区:PST / PDT
*表/
常量字符串payPalDateRegex ​​= @(小于时间> \d {1,2}:\d {2 }:\d {2})\s(小于日期>(小于
嗯> [A-ZA-z\] {3,5}?)\s(小于? ; DD> \d {1,2}),? \s(小于?YYYY> \d {4}))\s(小于?TZ> [AZ] {0,3}) ;
//重要:以上线路断了两行格式 - 在归队代码编辑器
//例子5时49分56秒2009年10月18日PDT
// 20:48: 22日2009年12月25日PST
匹配dateMatch = Regex.Match(rawPayPalDate,payPalDateRegex,RegexOptions.IgnoreCase);
DateTime的时间,日期= DateTime.MinValue;
//检查,看看是否正则表达式模式匹配提供的字符串
如果(dateMatch.Success)
{
//从正则表达式匹配群体$提取日期的相关部分; b $ b串rawDate = dateMatch.Groups [日]值;
串rawTime = dateMatch.Groups [时间]值;
串TZ = dateMatch.Groups [TZ]值。

//创建日期和时间值
如果(DateTime.TryParse(rawTime,超时时间)及和放大器; DateTime.TryParse(rawDate,过时))
$ { b $B∥加上时间日期值来获得datetime值
日期= date.Add(新的TimeSpan(time.Hour,time.Minute,time.Second));
//调整为PDT时区。通过0到localUtcOffset获得UTC / GMT
INT偏移= localUtcOffset + 7; // PDT = UTC-7,PST = UTC-8
如果(TZ ==PDT)//太平洋夏令时
日期= date.AddHours(偏移);
,否则//太平洋标准时间
日期= date.AddHours(偏移+ 1);
}
}
返回日期;
}


解决方案

我没有做过任何自2006年以来C#,所以这段代码可能不编译。测试一下你飞之前!



 公共静态的DateTime ConvertPayPalDateTime(字符串payPalDateTime)
{
//获取的偏移。
//如果C#支持对字符串的切换,它可能是更明智的这样做。
INT抵消;
如果(payPalDateTime.EndsWith(PDT))
{
偏差= 7;
}
,否则如果(payPalDateTime.EndsWith(PST))
{
偏差= 8;
}
,否则
{
抛出一些例外;
}

//我们解析的时区,所以从字符串中删除它。
payPalDatetime = payPalDateTime.Substring(0,payPalDateTime.Length-4);

//相同格式如上述,但具有的PST / PDT除去。
的String [] =的DateFormats {HH:MM:SS MMM DD,YYYY,HH:MM:SS MMM DD,YYYY};

//解析日期。如果失败抛出异常。
DateTime的RET = DateTime.ParseExact(payPalDateTime,的DateFormats,新的CultureInfo(EN-US),DateTimeStyles.None,出outputDateTime);

//添加偏移量,使它成为一个通用的时间。
返回ret.AddHours(偏移).SpecifyKind(DateTimeKind.Universal);
}


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://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. 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. Also the code above doesn't handle PDT properly (if converted to UTC).

Update2. Apparently, at least in previous versions, the sandbox would return "Feb." while the live returns "Feb". Lol. Someone save me!

Update3. 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. 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. 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);
}

这篇关于我如何把PayPal的HH:MM:(。)SS DD嗯YYYY PST / PDT到C#UTC日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆