104 lines
3.2 KiB
C#
104 lines
3.2 KiB
C#
using System;
|
|
using System.Text;
|
|
|
|
|
|
namespace rockfishCore.Util
|
|
{
|
|
public static class DateUtil
|
|
{
|
|
public const string DATE_TIME_FORMAT = "MMMM dd, yyyy h:mm tt";
|
|
public const string DATE_ONLY_FORMAT = "D";
|
|
|
|
//Unix epoch converters
|
|
public static string EpochToString(long? uepoch, string formatString = null)
|
|
{
|
|
if (uepoch == null) return string.Empty;
|
|
if (formatString == null)
|
|
formatString = DATE_ONLY_FORMAT;
|
|
return DateTimeOffset.FromUnixTimeSeconds(uepoch.Value).DateTime.ToString(formatString);
|
|
}
|
|
public static DateTime EpochToDate(long? uepoch)
|
|
{
|
|
DateTime dt = DateTime.Now;
|
|
if (uepoch == null) return DateTime.MinValue;
|
|
return DateTimeOffset.FromUnixTimeSeconds(uepoch.Value).DateTime;
|
|
}
|
|
|
|
public static long DateToEpoch(DateTime dt)
|
|
{
|
|
DateTimeOffset dto = new DateTimeOffset(dt);
|
|
return dto.ToUnixTimeSeconds();
|
|
}
|
|
|
|
public static long? DateTimeOffSetNullableToEpoch(DateTimeOffset? dt)
|
|
{
|
|
if (dt == null)
|
|
{
|
|
return null;
|
|
}
|
|
DateTimeOffset dto = dt.Value;
|
|
return dto.ToUnixTimeSeconds();
|
|
}
|
|
|
|
|
|
public static string ISO8601StringToLocalDateTime(string s)
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(s))
|
|
{
|
|
return DateTimeOffset.Parse(s).DateTime.ToLocalTime().ToString(DATE_TIME_FORMAT);
|
|
}
|
|
return string.Empty;
|
|
}
|
|
|
|
public static long? ISO8601StringToEpoch(string s)
|
|
{
|
|
DateTimeOffset? dto = ISO8601StringToDateTimeOffset(s);
|
|
if (dto == null)
|
|
return null;
|
|
return ((DateTimeOffset)dto).ToUnixTimeSeconds();
|
|
|
|
}
|
|
|
|
|
|
///////////////////////
|
|
//This method correctly interprets iso8601 strings to a datetimeoffset
|
|
public static DateTimeOffset? ISO8601StringToDateTimeOffset(string s)
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(s))
|
|
{
|
|
DateTimeOffset dto = DateTimeOffset.ParseExact(s, new string[] { "yyyy-MM-dd'T'HH:mm:ss.FFFK" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
|
|
return dto;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
|
|
|
|
public static long NowAsEpoch()
|
|
{
|
|
DateTimeOffset dto = new DateTimeOffset(DateTime.Now);
|
|
return dto.ToUnixTimeSeconds();
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// An internally consistent empty or not relevant date marker:
|
|
/// January 1st 5555
|
|
/// Used for RAVEN key generation
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public static DateTime EmptyDateValue
|
|
{
|
|
get
|
|
{
|
|
return new DateTime(5555, 1, 1);
|
|
//Was going to use MaxValue but apparently that varies depending on culture
|
|
// and Postgres has issues with year 1 as it interprets as year 2001
|
|
// so to be on safe side just defining one for all usage
|
|
}
|
|
}
|
|
|
|
//eoc
|
|
}
|
|
//eons
|
|
} |