How to convert Json Epoch date string to C# DateTime

 

The method below converts a Json Epoch Date string to a .NET string with a given format.

        public string JsonEpochDateToDateTime(string jsonEpochDate, string resultFormat)
        {
            string result = string.Empty;

            if (jsonEpochDate.Contains("Date(") && jsonEpochDate.Contains(")"))
            {
                jsonEpochDate = jsonEpochDate.Replace("Date(", string.Empty).Replace(")", string.Empty);
            }

            long milliseconds = 0;
            long.TryParse(jsonEpochDate, out milliseconds);

            if (milliseconds > 0)
            {
                var epochDate = new DateTime(1970, 1, 1);

                result = epochDate.AddMilliseconds(milliseconds).ToLocalTime().ToString(resultFormat);
            }

            return result;
        }

 

Usage example

var convertedDate = JsonEpochDateToDateTime("Date(1553209200000)", "dd-MM-yyyy");

 

Results in : 22-03-2019

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>