C#中,時間格式轉化,ticks,datetime

龐順龍發表於2019-05-11

C#中,時間格式轉化,ticks,datetime

/// <summary>
/// 轉換為ticks 格式
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static string ChangeDateTimeToTicks(DateTime? dateTime)
{
	if (dateTime != null)
	{
		DateTime dtime = (DateTime)dateTime;
		DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
		TimeSpan toNow = dtime.Subtract(dtStart);
		string timeStamp = toNow.Ticks.ToString();
		return timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
	}
	RETURN "";
}

/// <summary>
/// 轉換為時間格式
/// </summary>
/// <param name="ticksTime"></param>
/// <returns></returns>
public static DateTime ChangeTicksToDateTime(string ticksTime)
{
	if (!string.IsNullOrEmpty(ticksTime))
	{
		DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
		long lTime = long.Parse(ticksTime + "0000000");
		TimeSpan toNow = new TimeSpan(lTime);
		return dtStart.Add(toNow);
	}
	return DateTime.Now;
}

內容均為作者獨立觀點,不代表八零IT人立場,如涉及侵權,請及時告知。

相關文章