Extract Date from String - CSharp System

CSharp examples for System:DateTime Format

Description

Extract Date from String

Demo Code


using System.Web;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Extensions;
using System.Web.Mvc;
using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System;/* w w w . jav a2  s .  c  om*/

public class Main{
        private static DateTime ExtractDate(string input, string pattern, CultureInfo culture)
        {
            DateTime dt = DateTime.MinValue;
            var regex = new Regex(pattern);
            if (regex.IsMatch(input))
            {
                var matches = regex.Matches(input);
                var match = matches[0];
                var ms = Convert.ToInt64(match.Groups[1].Value);
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                dt = epoch.AddMilliseconds(ms);

                // adjust if time zone modifier present
                if (match.Groups.Count > 2 && !String.IsNullOrEmpty(match.Groups[3].Value))
                {
                    var mod = DateTime.ParseExact(match.Groups[3].Value, "HHmm", culture);
                    if (match.Groups[2].Value == "+")
                    {
                        dt = dt.Add(mod.TimeOfDay);
                    }
                    else
                    {
                        dt = dt.Subtract(mod.TimeOfDay);
                    }
                }

            }
            return dt;
        }
        /// <summary>
        /// Determines whether [is null or empty] [the specified s].
        /// </summary>
        /// <param name="s">The s.</param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string s)
        {
            if (s == null) return true;
            if (s.Trim() == string.Empty) return true;
            return false;
        }
}

Related Tutorials