c#时间戳相互转换

  /// <summary>
    /// 获取时间戳
    /// </summary>
    /// <returns></returns>
    public static string GetTimeSpan(System.DateTime time)
    {
        long ts = GetUnixTime(time);
        return ts.ToString();
    }

    /// <summary>  
    /// 将DateTime时间格式转换为Unix时间戳格式  
    /// </summary>
    /// <param name="time">时间</param>  
    /// <returns>long</returns>  
    public static long GetUnixTime(System.DateTime time)
    {
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
        long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
        return t;
    }
    /// <summary>        
    /// 将Unix时间戳转为C#时间格式      
    /// </summary>
    /// <param name="timeSpan"></param>        
    /// <returns></returns>        
    public static DateTime GetDateTimeFromUnix(string timeSpan)
    {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(timeSpan + "0000");
        TimeSpan toNow = new TimeSpan(lTime);
        return dtStart.Add(toNow);
    }

/// <summary>
/// 创建时间
/// </summary>
public string createTime { get; set; }

public DateTime _createTime {
get
{
if (string.IsNullOrEmpty(this.createTime))
return DateTime.MinValue;
return TimerTool.GetDate

 /// <summary>
        /// 根据字节长度来截取字符串
        /// </summary>
        ///<param name="origStr">原始字符串</param>
        ///<param name="length">提取前length个字节</param>
        /// <returns></returns>
        public static String CutByteString(string origStr, int length)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(origStr);
            int n = 0; //  表示当前的字节数
            int i = 0; //  要截取的字节数
            for (; i < bytes.GetLength(0) && n < length; i++)
            {
                //  偶数位置,如0、2、4等,为UCS2编码中两个字节的第一个字节
                if (i % 2 == 0)
                {
                    n++; //  在UCS2第一个字节时n加1
                }
                else
                {
                    //  当UCS2编码的第二个字节大于0时,该UCS2字符为汉字,一个汉字算两个字节
                    if (bytes[i] > 0)
                    {
                        n++;
                    }
                }
            }
            //  如果i为奇数时,处理成偶数
            if (i % 2 == 1)
            {
                //  该UCS2字符是汉字时,去掉这个截一半的汉字

                if (bytes[i] > 0)
                    i = i - 1;

                //  该UCS2字符是字母或数字,则保留该字符
                else
                    i = i + 1;
            }
            return Encoding.Unicode.GetString(bytes, 0, i);
        }

   var countlen = System.Text.Encoding.Default.GetByteCount(LocalDataManager.Instance.UserModel.student.name);
                NameText.text = countlen > 12 ? CutByteString(LocalDataManager.Instance.UserModel.student.name, 12) : LocalDataManager.Instance.UserModel.student.name;

TimeFromUnix(this.createTime);
}
}

猜你喜欢

转载自www.cnblogs.com/DSC1991/p/11593338.html