In many cases, the date is not saved directly, but saved as a Unix timestamp for storage, the advantage is that only one long-type number can be used for storage, saving space. In this case, the Unix Timestamp and datetime must be converted. In Windows Phone, Microsoft provides the timezoneinfo class, which can achieve this well.
The following is a class for mutual conversion of time formats. Four functions are provided to process time conversion, which is very comfortable to use:
using System;
namespace Utilities
{
public class UnixTimestampConverter
{
public static readonly DateTime UnixTimestampLocalZero = System.TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local);
public static readonly DateTime UnixTimestampUtcZero = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long ConvertLocalToTimestamp(DateTime datetime)
{
return (long)(datetime - UnixTimestampLocalZero).TotalMilliseconds;
}
public static long ConvertUtcToTimestamp(DateTime datetime)
{
return (long)(datetime - UnixTimestampUtcZero).TotalMilliseconds;
}
public static DateTime ConvertLocalFromTimestamp(long timestamp)
{
return UnixTimestampLocalZero.AddMilliseconds(timestamp);
}
public static DateTime ConvertUtcFromTimestamp(long timestamp)
{
return UnixTimestampUtcZero.AddMilliseconds(timestamp);
}
}
}