using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace CZFW.Core { public static class Utility { public static TType Parse(object value, TType defaultValue = default(TType)) { if (value == null || value == DBNull.Value || string.IsNullOrWhiteSpace(value.ToString())) return defaultValue; Type type = typeof(TType); Type underlyingType = Nullable.GetUnderlyingType(type); return (TType)Convert.ChangeType(value.ToString(), underlyingType ?? type); } public static long GetUnixTimeTick(DateTime? date = null) { if (date == null) { date = DateTime.Now; } var timespan = date.Value.Subtract(new DateTime(1970, 1, 1)); return timespan.Ticks; } public static string GenerateTreeMark(string parentMark = null) { if (string.IsNullOrEmpty(parentMark)) parentMark = "0"; var ticks = Utility.GetUnixTimeTick(); var mark = $"{parentMark}${ticks.ToString()}$"; return mark; } public static string Round(object obj) { var dnum = Parse(obj); var num = Math.Round(dnum); return num.ToString(System.Globalization.CultureInfo.InvariantCulture); } public static string GetNowString(string format = "yyyy/MM/dd hh:mm:ss") { var now = DateTime.Now; var nowStr = now.ToString(format, new CultureInfo("en-US")); return nowStr; } public static string GetCnNowString(string format = "yyyy/MM/dd hh:mm:ss") { var now = DateTime.Now; var nowStr = now.ToString(format, new CultureInfo("zn-CN")); return nowStr; } public static string GetNowStringForSql(string format = "yyyy/MM/dd hh:mm:ss") { var res = $"'{GetNowString(format)}'"; return res; } /// /// 格式化显示时间为几个月,几天前,几小时前,几分钟前,或几秒前 /// /// 要格式化显示的时间 /// 几个月,几天前,几小时前,几分钟前,或几秒前 public static string DateStringFromNow(DateTime dt) { TimeSpan span = DateTime.Now - dt; if (span.TotalDays > 60) { return dt.ToShortDateString(); } if (span.TotalDays > 30) { return "1个月前"; } if (span.TotalDays > 14) { return "2周前"; } if (span.TotalDays > 7) { return "1周前"; } if (span.TotalDays > 1) { return $"{(int)Math.Floor(span.TotalDays)}天前"; } if (span.TotalHours > 1) { return $"{(int)Math.Floor(span.TotalHours)}小时前"; } if (span.TotalMinutes > 1) { return $"{(int)Math.Floor(span.TotalMinutes)}分钟前"; } return span.TotalSeconds >= 1 ? $"{(int)Math.Floor(span.TotalSeconds)}秒前" : "刚刚"; } public static bool IsEmpty(this object value) { return string.IsNullOrEmpty(value?.ToString()); } public static string UpperCaseUrlEncode(string s) { char[] temp = System.Web.HttpUtility.UrlEncode(s).ToCharArray(); for (int i = 0; i < temp.Length - 2; i++) { if (temp[i] == '%') { temp[i + 1] = char.ToUpper(temp[i + 1]); temp[i + 2] = char.ToUpper(temp[i + 2]); } } return new string(temp); } } }