我收到了一個將多種日期格式轉換為單一格式的問題。
我已經獲得了一些開始的代碼,但我仍在學習 C# 的基礎知識并了解一般問題并進行了一些研究,但仍然不確定如何準確解決問題,如果有人可以提供一些指導或建議我將不勝感激,謝謝。
using System;
using System.Collections.Generic;
namespace CommonDateFormat
{
public class DateTransform
{
public static List<string> TransformDateFormat(List<string> dates)
{
throw new InvalidOperationException("Waiting to be implemented.");
}
static void Main(string[] args)
{
var input = new List<string> { "2010/02/20", "19/12/2016", "11-18-2012", "20130720" };
DateTransform.TransformDateFormat(input).ForEach(Console.WriteLine);
}
}
}
問題圖片
uj5u.com熱心網友回復:
讓我們從轉換 single 開始DateTime:
- 我們可以
TryParseExact將字串輸入DateTime - 然后我們可以表示
DateTime成所需的“標準”格式:
using System.Globalization;
using System.Linq;
...
private static string ConvertToStandard(string value) {
if (DateTime.TryParseExact(value,
//TODO: add more formats here if you want
new string[] { "yyyy/M/d", "d/M/yyyy", "M-d-yyyy", "yyyyMMdd"},
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out var date))
return date.ToString("yyyyMMdd"); //TODO: Put the right format here
else // parsing failed. You may want to throw new ArgumentException here
return value;
}
如果我們有一個,List<string>我們可以在Linq的幫助下查詢它:
List<string> original = new List<string>() {
"2010/02/20", "19/12/2016", "11-18-2012", "20130720",
};
var result = original.Select(item => ConvertToStandard(item));
// Let's have a look:
Console.Write(string.Join(", ", result));
或者如果你想要一個方法:
public static List<string> TransformDateFormat(List<string> dates) {
if (dates == null)
throw new ArgumentNullException(nameof(dates));
return dates.Select(s => ConvertToStandard(s)).ToList();
}
結果:(小提琴)
20100220, 20161219, 20121118, 20130720
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/396951.html
上一篇:跟蹤從月份開始日期開始的周間隔
