[英]Convert date format 01/05/2018 and 01/may/2018 to (dd/mm/yyyy) format and save same format into excel using c#
我有兩種類型的日期格式,例如01/05/2018和01 / may / 2018。 我想將兩種格式都轉換為(dd / MM / yyyy),如何將其轉換並保存為Excel文件。 我在將數據保存到excel中時遇到問題,保存的格式不正確,它的更改像第一個月,有時第一個日期是第一個,代碼是:-mystring = mystring.tostring.parse(“ dd / MM / yyyy”)
使用DateTime.ParseExact時,可以提供幾種 formats
。 所以,你可以解析初始字符串到DateTime
,然后格式化 DateTime
成需要的格式。
string[] tests = new string[] {
"01/05/2018",
"01/may/2018",
};
string[] formats = new string[] {
"d/M/yyyy", // try this format first
"d/MMMM/yyyy", // on fail try this one etc.
};
string[] results = tests
.Select(item => DateTime.ParseExact(item,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal))
.Select(date => date.ToString("dd'/'MM'/'yyyy")) // '/' - to preserve /
.ToArray();
Console.Write(Environment.NewLine, results);
結果:
01/05/2018
01/05/2018
我相信您必須這樣做:
targetRange.NumberFormat = "dd/MM/yyyy";
其中targetRange
是您想要具有所需日期格式的Cell
或Column
格式還必須是Excel能夠理解的格式,並且這並不總是與C#使用的格式相同
我有類似的問題,我嘗試了下面的代碼
DateTime date = DateTime.Now;
string formattedDate = date.ToString("dd'/'MM'/'yyyy");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.