how convert unix timestamp to datetime

回眸只為那壹抹淺笑 提交于 2019-12-05 12:39:49

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.

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;
 }

Just use DateTimeOffset

DateTimeOffset date = DateTimeOffset.FromUnixTimeSeconds(1415115303410)

Ofiris
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.

Try This

DateTime date = new DateTime(Convert.ToInt64("1415115303410"));

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.

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"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!