public static class DateTimeFormatUtils
{
private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static CultureInfo CurrentCulture => Thread.CurrentThread.CurrentCulture;
private static CultureInfo InvariantCulture => CultureInfo.InvariantCulture;
public static DateTime ToDateTime(string str)
{
return DateTime.Parse(str, CurrentCulture.DateTimeFormat);
}
public static DateTime ToDateTime(string str, DateTimeStyles dateTimeStyle)
{
return DateTime.Parse(str, CurrentCulture.DateTimeFormat, dateTimeStyle);
}
public static DateTime ToDateTime(string str, string format)
{
return DateTime.ParseExact(str, format, CurrentCulture.DateTimeFormat);
}
public static DateTime ToDateTime(string str, string format, DateTimeStyles dateTimeStyle)
{
return DateTime.ParseExact(str, format, CurrentCulture.DateTimeFormat, dateTimeStyle);
}
public static string ToString(DateTime dateTime)
{
return dateTime.ToString(CurrentCulture.DateTimeFormat);
}
public static string ToString(DateTime dateTime, string format)
{
return dateTime.ToString(format, CurrentCulture.DateTimeFormat);
}
public static string ToLongDateTimeString(DateTime dateTime)
{
return ToString(DateTime.Now, "F");
}
public static string ToLongDateString(DateTime dateTime)
{
return ToString(DateTime.Now, "D");
}
public static string ToLongTimeString(DateTime dateTime)
{
return ToString(DateTime.Now, "T");
}
public static string ToKSQlFormat(this DateTime dateTime)
{
return "{ts'" + dateTime.ToString("yyyy-MM-dd HH:mm:ss") + "'}";
}
public static bool IsValidDate(this DateTime dateTime)
{
if (dateTime.IsNullOrEmpty())
{
return false;
}
if (dateTime == DateTime.MinValue)
{
return false;
}
if (dateTime.ToString("yyyy-MM-dd") == "1900-01-01")
{
return false;
}
return true;
}
public static DateTime BeginDateTimeOfDay(this DateTime dateTime)
{
return Convert.ToDateTime(dateTime.ToString("yyyy-MM-dd") + " 00:00:00");
}
public static DateTime EndDateTimeOfDay(this DateTime dateTime)
{
return Convert.ToDateTime(dateTime.ToString("yyyy-MM-dd") + " 23:59:59");
}
public static long CurrentTimeMillis()
{
return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
}
public static long GetTimestamp(this DateTime dt)
{
return CurrentTimeMillis() / 1000;
}
}
C# 日期格式化工具类型扩展
最新推荐文章于 2023-09-03 18:11:17 发布
这个类库包含了一系列用于日期时间转换和格式化的静态方法,如`ToDateTime`、`ToString`、`ToLongDateTimeString`等,支持自定义格式和DateTimeStyles。还提供了检查日期有效性、获取一天的开始和结束时间、以及获取当前时间毫秒数和时间戳的方法。对于SQL格式的日期时间处理,有一个`ToKSQlFormat`方法,将日期时间转换为特定的字符串格式。
摘要由CSDN通过智能技术生成