.net 更改日期格式

來源:互聯網
上載者:User

標籤:

樣本:更改日期格式

下面的程式碼範例使用 Regex.Replace 方法將 mm/dd/yy 格式的日期替換為 dd-mm-yy 格式的日期。

static string MDYToDMY(string input) {     return Regex.Replace(input,          "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",         "${day}-${month}-${year}");}

下面的代碼示範如何在應用程式中調用 MDYToDMY 方法。

using System;using System.Globalization;using System.Text.RegularExpressions;public class Class1{   public static void Main()   {      string dateString = DateTime.Today.ToString("d",                                         DateTimeFormatInfo.InvariantInfo);      string resultString = MDYToDMY(dateString);      Console.WriteLine("Converted {0} to {1}.", dateString, resultString);   }   static string MDYToDMY(string input)    {        return Regex.Replace(input,             "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",            "${day}-${month}-${year}");   }}// The example displays the following output to the console if run on 8/21/2007://      Converted 08/21/2007 to 21-08-2007.

 


注釋

Regex模式 \b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b 的含義如下表所示。

 

模式

說明

\b

在單詞邊界處開始匹配。

(?<month>\d{1,2})

匹配一個或兩個十進位數字。 這是 month 擷取的群組。

/

匹配斜線符號。

(?<day>\d{1,2})

匹配一個或兩個十進位數字。 這是 day 捕獲的組。

/

匹配斜線符號。

(?<year>\d{2,4})

匹配兩個到四個十進位數。 這是 year 捕獲的組。

\b

在單詞邊界處結束匹配。

 

  


 

 

 

 

 

 

 

 

模式 ${day}-${month}-${year} 如下表所示定義了替換字串。

 

 

模式

說明

$(day)

添加由 day 擷取的群組捕獲的字串。

-

添加連字號。

$(month)

添加由 month 擷取的群組捕獲的字串。

-

添加連字號。

$(year)

添加由 year 擷取的群組捕獲的字串。

.net 更改日期格式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.