using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Runtime.Serialization.Json; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Web.Services.Protocols; using System.Security.Cryptography; using System.Text; using System.Web.SessionState; using System.Data; using System.Drawing.Imaging; using System.Drawing; using System.IO; using System.Data.SqlClient; using System.Configuration; using Org.BouncyCastle.Asn1.X509; public static class globalClass { public static string YearMonthDiff(DateTime self, DateTime target) { int years, months, days; // 因為只需取量,不決定誰大誰小,所以如果self < target時要交換將大的擺前面 if (self < target) { DateTime tmp = target; target = self; self = tmp; } // 將年轉換成月份以便用來計算 months = 12 * (self.Year - target.Year) + (self.Month - target.Month); // 如果天數要相減的量不夠時要向月份借天數補滿該月再來相減 if (self.Day < target.Day) { months--; days = DateTime.DaysInMonth(target.Year, target.Month) - target.Day + self.Day; } else { days = self.Day - target.Day; } // 天數計算完成後將月份轉成年 years = months / 12; months = months % 12; return years.ToString() + "歲" + months.ToString() + "月"; } public static int MonthDiff(DateTime self, DateTime target) { int years, months, days; // 因為只需取量,不決定誰大誰小,所以如果self < target時要交換將大的擺前面 if (self < target) { DateTime tmp = target; target = self; self = tmp; } // 將年轉換成月份以便用來計算 months = 12 * (self.Year - target.Year) + (self.Month - target.Month); // 如果天數要相減的量不夠時要向月份借天數補滿該月再來相減 if (self.Day < target.Day) { months--; days = DateTime.DaysInMonth(target.Year, target.Month) - target.Day + self.Day; } else { days = self.Day - target.Day; } return months; } public static string GetIPAddress() { System.Web.HttpContext context = System.Web.HttpContext.Current; string sIPAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(sIPAddress)) { return context.Request.ServerVariables["REMOTE_ADDR"]; } else { string[] ipArray = sIPAddress.Split(new Char[] { ',' }); return ipArray[0]; } } public static string CreateRandomCode(int Number) { string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; string[] allCharArray = allChar.Split(','); string randomCode = ""; Random rand = new Random(Guid.NewGuid().GetHashCode()); for (int i = 0; i <= Number - 1; i++) { int t = rand.Next(allCharArray.Length); randomCode += allCharArray[t]; } return randomCode; } public static string appsettings(string key) { return ConfigurationManager.ConnectionStrings[key].ConnectionString; } public static string SHA256_Encode(string value) { byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(value); try { SHA256 sha256 = new SHA256CryptoServiceProvider(); byte[] retVal = sha256.ComputeHash(bytValue); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("GetSHA256HashFromString() fail,error:" + ex.Message); } } }