using Newtonsoft.Json.Linq; using System.Globalization; using static System.Runtime.InteropServices.JavaScript.JSType; namespace DS.Module.Core.Extensions; public static class DateTimeExtension { /// /// 时间戳起始日期 /// public static readonly DateTime TimestampStart = new(1970, 1, 1, 0, 0, 0, 0); /// /// 转换为时间戳 /// /// /// 是否使用毫秒 /// public static long ToTimestamp(this DateTime dateTime, bool milliseconds = false) { var timestamp = dateTime.ToUniversalTime() - TimestampStart; return (long)(milliseconds ? timestamp.TotalMilliseconds : timestamp.TotalSeconds); } /// /// 获取周几 /// /// /// public static string GetWeekName(this DateTime datetime) { var day = (int)datetime.DayOfWeek; var week = new string[] { "周日", "周一", "周二", "周三", "周四", "周五", "周六" }; return week[day]; } public static int GetWeekOfYear(this DateTime dt, CultureInfo ci) { // 获取与当前环境区域性相关的 CultureInfo 对象,或者你可以使用特定的区域性,例如 "zh-CN" CultureInfo cultureInfo = new CultureInfo("zh-CN"); // 从 CultureInfo 对象获取 Calendar 对象 Calendar calendar = ci.Calendar; // 定义 CalendarWeekRule,通常是使用当前文化的 DateTimeFormat CalendarWeekRule calendarWeekRule = cultureInfo.DateTimeFormat.CalendarWeekRule; // 一周的第一天 DayOfWeek firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek; // 获取指定日期在一年中的周数 int weekOfYear = calendar.GetWeekOfYear(dt, calendarWeekRule, firstDayOfWeek); return weekOfYear; } /// /// 获取datetime值 /// /// /// /// public static DateTime? GetDateTimeValue(this JObject jobj, string prop) { var jt = jobj[prop]; if (jt == null) { return null; } var strVal = jt.ToString(); DateTime rtnVal = DateTime.MinValue; if (DateTime.TryParse(strVal, out rtnVal)) { return rtnVal; } return null; } }