Generate the UNIX style timestamp for DateTime.UtcNow
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Drawing;
public static class Utility
{
public static DateTime ConvertToDateTime(string timestamp)
{
var dtbase = new DateTime(1970, 1, 1, 8, 0, 0, 0); // UTC +8
return dtbase.AddSeconds(double.Parse(timestamp));
}
/// <summary>
/// Generate the UNIX style timestamp for DateTime.UtcNow
/// </summary>
/// <returns></returns>
public static string GenerateTimeStamp(DateTime dt, bool isMiliseconds = false)
{
TimeSpan ts = dt - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
if (isMiliseconds)
{
ts = dt - new DateTime(1970, 1, 1, 8, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
else
{
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
}
/// <summary>
/// Generate the UNIX style timestamp for DateTime.UtcNow
/// </summary>
/// <returns></returns>
public static string GenerateTimeStamp()
{
return GenerateTimeStamp(DateTime.UtcNow);
}
}
Related examples in the same category