zoukankan      html  css  js  c++  java
  • .net 更改日期格式

    示例:更改日期格式

    下面的代码示例使用 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.

    注释

    正则表达式模式 (?<month>d{1,2})/(?<day>d{1,2})/(?<year>d{2,4}) 的含义如下表所示。

    模式

    说明

    

    在单词边界处开始匹配。

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

    匹配一个或两个十进制数字。 这是 month 捕获组。

    /

    匹配左斜线。

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

    匹配一个或两个十进制数字。 这是 day 捕获的组。

    /

    匹配左斜线。

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

    匹配两个到四个十进制数。 这是 year 捕获的组。

    

    在单词边界处结束匹配。

     
     

     

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

    模式

    说明

    $(day)

    添加由 day 捕获组捕获的字符串。

    -

    添加连字符。

    $(month)

    添加由 month 捕获组捕获的字符串。

    -

    添加连字符。

    $(year)

    添加由 year 捕获组捕获的字符串。

  • 相关阅读:
    vue-生命周期图示 注解
    vue-组件嵌套之——父组件向子组件传值
    vue-框架模板的源代码注释
    vue-小demo、小效果 合集(更新中...)
    Gulp-自动化编译sass和pug文件
    JS
    Node.js- sublime搭建node的编译环境
    sublime--package control的配置与插件安装
    git-常用命令一览表
    java面试题:jvm
  • 原文地址:https://www.cnblogs.com/Dylanblogs/p/4266503.html
Copyright © 2011-2022 走看看