Parse Json Date - CSharp System

CSharp examples for System:DateTime Parse

Description

Parse Json Date

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;//from w  w  w. j a v a2s  .  com

public class Main{
        public static DateTime ParseJsonDate(this string input, CultureInfo culture)
        {
            input = input.Replace("\n", "");
            input = input.Replace("\r", "");

            input = input.RemoveSurroundingQuotes();

            long? unix = null;
            try
            {
                unix = Int64.Parse(input);
            }
            catch (Exception) { };
            if (unix.HasValue)
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                return epoch.AddSeconds(unix.Value);
            }

            if (input.Contains("/Date("))
            {
                return ExtractDate(input, @"\\?/Date\((-?\d+)(-|\+)?([0-9]{4})?\)\\?/", culture);
            }

            if (input.Contains("new Date("))
            {
                input = input.Replace(" ", "");
                // because all whitespace is removed, match against newDate( instead of new Date(
                return ExtractDate(input, @"newDate\((-?\d+)*\)", culture);
            }

            return ParsePickerDate(input);
        }
        /// <summary>
        /// Remove leading and trailing " from a string
        /// </summary>
        /// <param name="input">String to parse</param>
        /// <returns>String</returns>
        public static string RemoveSurroundingQuotes(this string input)
        {
            if (input.StartsWith("\"") && input.EndsWith("\""))
            {
                // remove leading/trailing quotes
                input = input.Substring(1, input.Length - 2);
            }
            return input;
        }
}

Related Tutorials