You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.5 KiB
C#

using Newtonsoft.Json.Linq;
using System.Globalization;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace DS.Module.Core.Extensions;
1 year ago
public static class DateTimeExtension
{
/// <summary>
/// 时间戳起始日期
/// </summary>
public static readonly DateTime TimestampStart = new(1970, 1, 1, 0, 0, 0, 0);
/// <summary>
/// 转换为时间戳
/// </summary>
/// <param name="dateTime"></param>
/// <param name="milliseconds">是否使用毫秒</param>
/// <returns></returns>
public static long ToTimestamp(this DateTime dateTime, bool milliseconds = false)
{
var timestamp = dateTime.ToUniversalTime() - TimestampStart;
return (long)(milliseconds ? timestamp.TotalMilliseconds : timestamp.TotalSeconds);
}
/// <summary>
/// 获取周几
/// </summary>
/// <param name="datetime"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 获取datetime值
/// </summary>
/// <param name="jobj"></param>
/// <param name="prop"></param>
/// <returns></returns>
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;
}
1 year ago
}