【问题标题】:Swapping the month and the year in a 4 digit date string在 4 位日期字符串中交换月份和年份
【发布时间】:2020-10-21 18:15:07
【问题描述】:

基本上,我接受到期日期。假设 12/24。我提交给它的 API 非常具体,没有斜线,而且必须是年份。

删除斜线很容易:

var dt = Convert.ToString(payment.ExpirationDate.Replace("/", string.Empty));

所以,现在我的字符串中有一个 4 位数字,我想我也可以 Convert.ToInt32 并有一个 int。

但无论哪种方式,我都不确定如何拆分和交换。对于字符串,它需要一个字符,而不是一个数字。

【问题讨论】:

  • 尝试用/ 分割字符串,然后你将拥有一个可以调用Reverse 的数组来重新排序。如果它仍然必须是一个字符串,您可以使用 / 或其他任何东西加入数组。 api 需要的具体格式是什么?
  • 不清楚你在问什么。 您尝​​试过什么?您需要帮助的哪一部分?语言文档和许多解释如何操作字符串的教程中有大量信息。请发布您为解决问题而编写的代码,说明该代码的作用、您希望它做什么以及具体您需要什么帮助。
  • Console.WriteLine(DateTime.ParseExact("12/24", "MM/yy", CultureInfo.CurrentCulture).ToString("yyMM"));
  • 如果您当前有一个字符串,我不会使用 DateTime。您可能会遇到解析问题。例如,如果年份为 49 或更少,则默认为当前世纪。 50 或更高将是上个世纪。您还存在时区和偏移量的问题(诚然,如果您只有月份和年份,应该没有影响)。日期更容易编程为字符串,除非您对其进行操作(添加日期、转换偏移量等)。
  • @ps2goat 在下面的回答中添加了一种避免两位数问题的方法。

标签: c# datetime date-formatting


【解决方案1】:

由于您正在处理日期,您可能应该使用DateTime。这使您可以验证日期并生成所需的任何其他格式。

这样的事情应该可以完成:

string input = "12/24";
DateTime date = DateTime.ParseExact(input, "MM/yy", CultureInfo.CurrentCulture);
string output = date.ToString("yyMM");

如果您确定日期格式正确,请使用上述内容。如果没有,您可以使用以下方法进行验证:

bool isValid = DateTime.TryParseExact(input, "MM/yy", CultureInfo.CurrentCulture, 
                                      DateTimeStyles.None, out DateTime date);
if (isValid)
{
    string output = date.ToString("yyMM");
    //...
}
else { /* Do something about it */ }

为避免将世纪误认为 50 年或以上 (as addressed in the comments),您可以创建自定义 CultureInfo 并更改 TwoDigitYearMax 属性:

CultureInfo myCultureInfo = new CultureInfo(CultureInfo.CurrentCulture.LCID);
myCultureInfo.Calendar.TwoDigitYearMax = 2099;

然后,您将 myCultureInfo 而不是 CultureInfo.CurrentCulture 传递给 ParseExact()TryParseExact()

【讨论】:

    【解决方案2】:

    删除斜线后

    public static string ReverseString(this string s)
    {
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }
    

    例子:

    var dt = Convert.ToString(payment.ExpirationDate.Replace("/", string.Empty));
    var dt2 = dt.ReverseString();
    

    【讨论】:

      【解决方案3】:

      您可以使用ParseExact 将原始字符串转换为DateTime 对象:

      DateTime.ParseExact(payment.ExpirationDate, "MM/yy", null)
      

      这样,将DateTime 对象格式化为“yyMM”非常简单:

      datetime.ToString("yyMM")
      

      使用您提供的字符串的完整示例:

      Console.WriteLine(DateTime.ParseExact("12/24", "MM/yy", null).ToString("yyMM"));
      

      输出如下:

      2412
      

      【讨论】:

        【解决方案4】:

        使用正则表达式从两个单独变量中的输入字符串中提取年 + 月。然后,您可以根据需要重新排序/格式化它们。

        using System;
        using System.Text.RegularExpressions;
                            
        public class Program
        {
            public static void Main()
            {
                var regexTest = new Regex(@"(?<month>\d{2})/(?<year>\d{2})");
                var input = "12/24";
                var match = regexTest.Match(input);
                if(match.Success) {
                    var monthValue = match.Groups["month"];
                    var yearValue = match.Groups["year"];
                    Console.WriteLine($"{yearValue} - {monthValue}");
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2012-02-17
          • 2020-12-19
          • 1970-01-01
          • 2021-10-15
          • 1970-01-01
          • 2022-08-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多