如何在 C# 中轉換 dateTime 格式? (How do I convert dateTime format in C#?)


問題描述

如何在 C# 中轉換 dateTime 格式? (How do I convert dateTime format in C#?)

這是

string date = "07‑Feb‑2020"; 

我不確定如何將其轉換為

"2020‑02‑07 00:00:00"

表示形式


參考解法

方法 1:

ParseExact into DateTime then format to the desired string representation:

  string date = "07‑Feb‑2020";

  string result = DateTime
    .ParseExact(date, "dd‑MMM‑yyyy", CultureInfo.InvariantCulture)
    .ToString("yyyy‑MM‑dd HH:mm:ss");

方法 2:

Use Parse Exact

DateTime.ParseExact(date, "dd‑MMM‑yyyy", null);

方法 3:

Use DateTime:

 DateTime thisDate1 = new DateTime(2011, 6, 10);
 Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");

 DateTimeOffset thisDate2 = new DateTimeOffset(2011, 6, 10, 15, 24, 16, 
                                          TimeSpan.Zero);
 Console.WriteLine("The current date and time: {0:MM/dd/yy H:mm:ss zzz}", 
               thisDate2); 
 // The example displays the following output:
 //    Today is June 10, 2011.
 //    The current date and time: 06/10/11 15:24:16 +00:00

Code is from Microsoft docs

You can create any formatting you wish to do

(by Nawaf MominDmitry BychenkoAtkLukáš Machajdík)

參考文件

  1. How do I convert dateTime format in C#? (CC BY‑SA 2.5/3.0/4.0)

#datetime-format #.net #C#






相關問題

給定一個 DateTime 對象,如何獲取字符串格式的 ISO 8601 日期? (Given a DateTime object, how do I get an ISO 8601 date in string format?)

Праграма WPF наладжвае кароткую дату пры выкарыстанні stringformat={}{0:d} (WPF application customize shortdate when using stringformat={}{0:d})

使用 java.time.DateTimeFormatter 格式化 java Date,包括時間偏移 (Formating java Date with java.time.DateTimeFormatter including time offset)

# 如何使用 DateTime 類(處理轉換、格式、差異和時區) (# How to use the DateTime class (Dealing with Conversions, Formatting, Diffs, and Time zones))

從一種時間格式轉換為另一種時間格式 (Converting from one time format to the other)

如何將python中的數據框列對象轉換為日期時間格式 (How to convert a dataframe column object in python to date time format)

BeautifulSoup:如何以 datwtime 格式獲取 youtube 視頻的發布日期時間? (BeautifulSoup: How to get publish datetime of a youtube video in datwtime format?)

如何在 C# 中轉換 dateTime 格式? (How do I convert dateTime format in C#?)

在 SQL 中的時間範圍之間獲取記錄的替代方法(計算財政年度) (Alternative ways to get records between a time frame in SQL (calculate fiscal year))

Elasticsearch 自定義日期時間格式,包括。序數 (Elasticsearch custom date time format incl. ordinal numbers)

我有一個 int 格式的日期 DDMMYYYY,我怎樣才能分隔日月年 (I have a date in int format DDMMYYYY, how can I separate day and month and year)

Intl.DateTimeFormat 中 dayPeriod 的參考 (Reference for dayPeriod in Intl.DateTimeFormat)







留言討論