我不知道该怎么做。 基本上,我接受有效期。假设是12/24。 我提交给它的API非常具体,没有斜线,并且年份必须是第一位。
删除斜线很容易:
var dt = Convert.ToString(payment.ExpirationDate.Replace("/", string.Empty));
所以,现在我在字符串中有一个4位数字,我想我也可以Convert.ToInt32
并有一个整数。
但是无论哪种方式,我都不确定如何拆分和交换。使用字符串时,它需要一个字符,而不是数字。任何帮助将不胜感激。
答案 0 :(得分:2)
由于您正在处理日期,因此可能应该使用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年(VS2013 or VS2015 shows "unspecified error"),您可以创建自定义的CultureInfo并更改TwoDigitYearMax
属性:
CultureInfo myCultureInfo = new CultureInfo(CultureInfo.CurrentCulture.LCID);
myCultureInfo.Calendar.TwoDigitYearMax = 2099;
然后,您将myCultureInfo
而不是CultureInfo.CurrentCulture
传递给ParseExact()
或TryParseExact()
。
答案 1 :(得分:0)
删除斜杠后
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();
答案 2 :(得分:0)
您可以分割字符串,然后反转输出。如果是个位数的月份,您也应该填充数字。
var dt = string.Join(string.Empty, payment.ExpirationDate
.Split("/").Select(s => s.PadLeft(2, '0')).Reverse());
对于您的示例,您将获得“ 12/24”的“ 2412”。对于“ 9/23”这样的个位数月份,您将获得“ 2309”。
答案 3 :(得分:0)
您可以使用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 :(得分:-1)
使用正则表达式从输入字符串的两个单独变量中提取年+月。然后,您可以根据需要对其进行重新排序/格式化。
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}");
}
}
}