csharp C#DateTime解析扩展方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp C#DateTime解析扩展方法相关的知识,希望对你有一定的参考价值。

namespace ExtensionMethods {
    using System;
    using System.Globalization;

    public static class DateTimeExtensions {
        public static DateTime ToDateTime(this string s, string format = "ddMMyyyy", string cultureString = "tr-TR") {
            try {
                var r = DateTime.ParseExact(
                    s: s, format: format, provider: CultureInfo.GetCultureInfo(cultureString));
                return r;
            } catch (FormatException) {
                throw;
            } catch (CultureNotFoundException) {
                throw; // Given Culture is not supported culture
            }
        }

        public static DateTime ToDateTime(this string s, string format, CultureInfo culture) {
            try {
                var r = DateTime.ParseExact(s: s, format: format, provider: culture);
                return r;
            } catch (FormatException) {
                throw;
            } catch (CultureNotFoundException) {
                throw; // Given Culture is not supported culture
            }

        }

    }
}

namespace SO {
    using ExtensionMethods;
    using System;
    using System.Globalization;

    class Program {
        static void Main(string[] args) {
            var mydate = "29021996";
            var date = mydate.ToDateTime(format: "ddMMyyyy"); // {29.02.1996 00:00:00}

            mydate = "2016 3";
            date = mydate.ToDateTime("yyyy M"); // {01.03.2016 00:00:00}

            mydate = "2016 12";
            date = mydate.ToDateTime("yyyy d"); // {12.01.2016 00:00:00}

            mydate = "2016/31/05 13:33";
            date = mydate.ToDateTime("yyyy/d/M HH:mm"); // {31.05.2016 13:33:00}

            mydate = "2016/31 Ocak";
            date = mydate.ToDateTime("yyyy/d MMMM"); // {31.01.2016 00:00:00}

            mydate = "2016/31 January";
            date = mydate.ToDateTime("yyyy/d MMMM", cultureString: "en-US"); // {31.01.2016 00:00:00}

            mydate = "11/شعبان/1437";
            date = mydate.ToDateTime(
                culture: CultureInfo.GetCultureInfo("ar-SA"),
                format: "dd/MMMM/yyyy"); // Weird :) I supposed dd/yyyy/MMMM but that did not work !?$^&*

            System.Diagnostics.Debug.Assert(date.Equals(new DateTime(year: 2016, month: 5, day: 18)));
        }
    }
}

以上是关于csharp C#DateTime解析扩展方法的主要内容,如果未能解决你的问题,请参考以下文章

csharp DateTime扩展方法

csharp C#中的DateTime

csharp C#_mongo_datetime_attributing.cs

csharp C#项目的有用扩展方法的运行列表。

csharp 简单的C#扩展方法,将驼峰大小写字符串转换为下划线表示法而不使用任何正则表达式

csharp C#:在.NET中合并,追加,扩展两个数组(csharp,mono)