Skip to main content

Creates a human-readable string that represents a given timestamp in a (ISO 8601) format that can be converted back to the correct value across time zones.

using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;

namespace Utils
{
    public static class DateTimeUtil
    {
        /// <summary>
        /// Creates a human-readable string that represents a given
        /// timestamp in a format that can be converted back to the
        /// correct value across time zones.
        /// The serialized timestamp can be converted back into a
        /// <see cref="DateTime"/> instance through the
        /// <see cref="ReadDateTime"/> method.
        /// </summary>
        /// <param name="value">Timestamp to be serialized.</param>
        /// <returns>String representation of the timestamp.</returns>
        public static string SerializeDateTime(DateTime value)
        {
            return value.ToString("o", CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// Parses a serialized timestamp that was created through the <see cref="SerializeDateTime"/> method.
        /// </summary>
        /// <param name="value">A string that represents a given time.</param>
        /// <returns>A corresponding timestamp.</returns>
        /// <remarks>This method works with local, UTC and unspecified timestamps.</remarks>
        public static DateTime ReadDateTime(string value)
        {
            return DateTime.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
        }
    }
}