将字符串转换为新格式



我正在运行一个 C# 应用程序,该应用程序以MM/DD/YYYY格式提取日期字符串,只是当一天小于 10 时,数据显示为MM/D/YYYY。(即:它提取2/4/2020..而不是2/04/2020(。

我将数据存储在strDateExtracted变量中。

当我粘贴/放置数据时,应用程序要求我将其放入MMDDYYYY

例如,如果我提取2/4/2020,应用程序希望我放入02042020

我需要将该字符串从MM/DD/YYYY转换为MMDDYYYY,如果 day 大于 9,则MMDYYYY转换为MM/0D/YYYY.

有什么想法吗?

我能想到两种可能的方法。

第一种方法,基本上将字符串转换为DateTime并将其格式化回所需的格式:

public string GetDate(string input)
{
return DateTime.Parse(input).ToString("MM/dd/yyyy");
}

另一种方法(可能是更快的方法(是自己拆分字符串并自行添加0

public string GetDate(string input)
{
var items = input.Split('/');
if(items[0].Length == 1)
{
items[0] = "0" + items[0];
}
if(items[1].Length == 1)
{
items[1] = "0" + items[1];
}
return string.Join("/", items);
}

请注意,这当然都是基于猜测,输入和所需的输出是字符串。

根据您的输入,我们假设输入将包含 8、9 或 10 个字符,并且格式正确,例如

12/12/2020 (10 chars)
2/12/2020 (9 chars)
12/2/2020 (9 chars)
2/2/2020 (8 chars)

我们可以创建一个 C# 8.0 开关表达式,该表达式使用输入上的范围/索引返回正确的字符串。这可以说是过度设计的,但对于避免由于字符串拆分等原因导致的分配可能很有用。

完整的程序如下,您可以使用此.NET Fiddle运行它。

using System;
namespace Dates
{
class Program
{
static void Main(string[] args)
{
var input = "12/12/2020";
Console.WriteLine(GetWithoutSlashes(input));
input = "2/12/2020";
Console.WriteLine(GetWithoutSlashes(input));
input = "12/2/2020";
Console.WriteLine(GetWithoutSlashes(input));
input = "2/2/2020";
Console.WriteLine(GetWithoutSlashes(input));
}
static string GetWithoutSlashes(string input)
{
return input.Length switch
{
// First two digits (month), third/fourth digits (day), last 4 digits (year)
10 => $"{input[..2]}{input[3..5]}{input[^4..]}",
9 => input[1] == '/'
// Single digit month with zero before it, double digit day, last 4 digit year
? $"0{input[0]}{input[2..4]}{input[^4..]}"
// First two digits for month, single digit day with a zero before it, year
: $"{input[..2]}0{input[3]}{input[^4..]}",
// Single digit month, day with zero before each, last 4 digit year
8 => $"0{input[0]}0{input[2]}{input[^4..]}",
_ => throw new ArgumentException("Bad input!", nameof(input))
};
}
}
}

最新更新