问题
I'm trying to convert this unix timestamp 1415115303410 in DateTime, in this way:
private static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
{
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp);
return dtDateTime;
}
But I get a wrong date: Date: {04/11/0045 00:00:00}
NOTE: dtDateTime.AddSeconds(unixTimeStamp) throws an exception.. my number is in Milliseconds.
with this online conversion tool http://www.epochconverter.com/ I get the right conversion:
04/11/2014 15:35:03 GMT+0:00
How I can convert this one?
回答1:
Your code is working just fine, as is. Here is a fiddle.
Everyone that is telling you to use AddSeconds
is wrong. The number you are giving us is clearly in milliseconds. There are 31,536,000 seconds in a year. 1415115303410 divided by 31536000 is 4487. There hasn't been 4,487 years passed since 1/1/1970.
回答2:
use AddSeconds instead of AddMilliseconds
private static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
{
System.DateTime dtDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);
return dtDateTime;
}
回答3:
Just use DateTimeOffset
DateTimeOffset date = DateTimeOffset.FromUnixTimeSeconds(1415115303410)
回答4:
public DateTime FromUnixTime(long unixTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(unixTime);
}
var date = FromUnixTime(1415115303410); // 11/4/2014 3:35:03 PM
Since your number is in milliseconds, Unix time, use AddMilliseconds
.
回答5:
Try This
DateTime date = new DateTime(Convert.ToInt64("1415115303410"));
回答6:
Microsoft continue thinking about us! All solutions to add seconds/milliseconds is not working with Visual Studio 2017 (.Net 4.6.1). But there is a new solution:
public static DateTime numStrToDate(String val)
{
DateTime dRet = new DateTime(1970, 1, 1, 0, 0, 0, 0);
long dSec;
if (long.TryParse(val, out dSec))
{
TimeSpan ts = new TimeSpan(dSec*10l);
dRet = dRet.Add(ts);
}
return dRet;
}
If you need a UTC time - just add 'System.DateTimeKind.Utc' to the DateTime constructor call.
回答7:
Date to Timestamp
DateTime date = DateTime.ParseExact(date_string, "dd/MM/yyyy H:mm:ss", null);
Double timestamp = Math.Truncate((date.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
Timestamp to Date
DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Unspecified);
dtDateTime = dtDateTime.AddSeconds(Double.Parse(arrayFinalResponse[i, 5])).ToLocalTime();
String date = dtDateTime.ToString("dd/MM/yyyy H:mm:ss", CultureInfo.GetCultureInfo("en-US"));
来源:https://stackoverflow.com/questions/28305153/how-convert-unix-timestamp-to-datetime