我正在尝试将当前年份+ 1午夜日期时间转换为unix时间戳。
因为我已经尝试了
DateTime currentTime = DateTime.Today;
DateTime yearEnd = new DateTime( currentTime.Year, 1,1,currentTime.Minute,currentTime.Hour,currentTime.Second,DateTimeKind.Local);
yearEnd = yearEnd.AddYears(1);
double t = (yearEnd.ToUniversalTime() - new DateTime(1970, 1, 1,0,0,0)).TotalMilliseconds;
以上代码正在返回1514782800000
,即Mon Jan 01 2018 05:00:00 UTC
和Mon Jan 01 2018 10:30:00 Local
(印度)
我期待的是它将时间转换为Mon Jan 01 2018 00:00:00
当地时间
答案 0 :(得分:1)
默认情况下DateTime
会创建Unspecified
DateTimeKind
,因此明确使用UTC有助于避免混淆。我试图以这种方式改写
DateTime currentTime = DateTime.UtcNow;
DateTime yearEnd = new DateTime( currentTime.Year, 1,1,0,0,0, DateTimeKind.Utc);
yearEnd = yearEnd.AddYears(1); // output DateTime has Utc Kind
var unixTimestamp = (yearEnd.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds;
Console.WriteLine(unixTimestamp);
输出为1514764800000
,转换为GMT: Monday, 1 January 2018 00:00:00
<强>更新强>
如果您需要将时间戳转换回DateTime
,您可以使用以下内容:
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp);
return dtDateTime; // still Utc Kind
}
用法示例,如果您需要转换为其他时区:
TimeZoneInfo infotime = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time (Mexico)"); // specify your desired timezone here
Console.WriteLine(TimeZoneInfo.ConvertTimeFromUtc(UnixTimeStampToDateTime(unixTimestamp), infotime));
答案 1 :(得分:0)
如果我理解你,你需要以下内容:
double result = new DateTime(currentTime.Year + 1, 1, 1, 0, 0, 0, DateTimeKind.Local).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
或改善了可读性
DateTime newYear = new DateTime(currentTime.Year + 1, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime uTSBegin = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
double result2 = newYear.Subtract(uTSBegin).TotalSeconds;