[英]C#, DateTime conversion
需要幫助將datetime對象轉換為特定格式。 它可能是重復的問題,但是我瀏覽了許多文章以及Stackoverflow中提供的問題和答案,但沒有得到答案。 當前我的日期格式為{dd / mm / yyyy 8:12:56 AM},這是默認的日期時間格式。 我想轉換為{mm / dd / yyyy 8:12:56 AM}格式。
DateTime searchDateTime = Datetime.Now.AddYears(-1));
string test = searchDateTime.ToString("dd-MMM-yyyy");
它給了我在ToString中給出的格式。
DateTime date = Convert.ToDateTime(test);
但是,當我嘗試將字符串轉換為datetime格式時,其返回的dd / mm / yyyy格式化日期。
嘗試使用DateTime.ParseExact
如果你想解析與已知的格式和字符串ToString
當你想表示DateTime
到所需的格式 :
using System.Globalization;
...
DateTime searchDateTime = new DateTime(2019, 2, 25, 16, 15, 45);
// Escape delimiters with apostrophes '..' if you want to preserve them
string test = searchDateTime.ToString(
"dd'-'MMM'-'yyyy' 'h':'mm':'ss' 'tt",
CultureInfo.InvariantCulture);
// Parse string with known format into DateTime
DateTime date = DateTime.ParseExact(
test,
"dd'-'MMM'-'yyyy' 'h':'mm':'ss' 'tt",
CultureInfo.InvariantCulture);
// Presenting DateTime as a String with the desired format
string result = date.ToString(
"MM'/'dd'/'yyyy' 'h':'mm':'ss' 'tt",
CultureInfo.InvariantCulture);
Console.WriteLine($"Initial: {test}");
Console.Write($"Final: {result}");
結果:
Initial: 25-Feb-2019 4:15:45 PM
Final: 02/25/2019 4:15:45 PM
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.