我正在嘗試以特定格式顯示當前日期。
例如,“包裹將在 ____________ 的 ___ 日,_____ 在公司商店交付。” 輸出將是“包裹將在(9 月),(2022 年)的這(29)天在公司商店交付。”。非常感謝您的幫助。
uj5u.com熱心網友回復:
DateTime擁有您需要的一切:
DateTime now = DateTime.Now;
string s = $"Package will be delivered this {now.Day} day of {now:MMMM}, {now.Year} at the company shop.";
對于完整的月份名稱,我使用MMMM 格式說明符。
如果您愿意,您可以對所有人使用自定義格式說明符:
string s = $"Package will be delivered this {now:dd} day of {now:MMMM}, {now:yyyy} at the company shop.";
uj5u.com熱心網友回復:
有了這個,從這里,
string GetDaySuffix(int day) =>
day switch
{
1 or 21 or 31 => "st",
2 or 22 => "nd",
3 or 23 => "rd",
_ => "th",
};
你可以做,
var now = DateTime.Now;
var legalDate = $"this {now:d}{GetDaySuffix(now.Day)} day of {now:MMMM}, {now:yyyy}";
筆記,
日期后綴代碼對文化不敏感,但由于您的文本似乎是英式風格的英語,我假設兩者都喜歡在月份中添加后綴,并且不需要其他語言的后綴(如果其他文化甚至去做?)
uj5u.com熱心網友回復:
Mine 解決方案是使用擴展方法,它會節省一些時間來撰寫包裝方法和傳遞日期和時間作為輸入。
結果:
Package will be delivered this 29 day of 09, 2022 at the company shop.
由于執行將如下:
global using ExtensionMethods;
Console.WriteLine(DateTime.Today.ToString("dd/MM/yyyy").ToCustomDateFormat());
擴展方法將是:
namespace ExtensionMethods
{
public static class MyExtensions
{
public static string ToCustomDateFormat(this string str)
{
string day = str.Substring(0, str.IndexOf('/'));
string month = str.Substring(str.IndexOf('/') 1, str.IndexOf('/', str.IndexOf('/')));
string year = str.Substring(str.LastIndexOf('/') 1, str.Length - str.LastIndexOf('/') - 1);
string result = $"Package will be delivered this {day} day of {month}, {year} at the company shop.";
return result;
}
}
}
與我 2.5 年的 c# 經驗相比,我的代碼和知識是否還可以。請不要覺得我 15 歲很粗魯。誰能建議我,我的時薪是多少。我需要學習哪些東西才能進入入門級?將非常感謝。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/510301.html
標籤:C#日期
