简体   繁体   中英

how to convert from millisecond to DateTime in c#

private static DateTime FromMS(long microSec)
{           
    long milliSec = (long)(microSec / 1000);
    DateTime startTime = new DateTime(1970, 1, 1);

    TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
    DateTime v = new DateTime(time.Ticks);

    DateTime result = new DateTime(startTime.Year + v.Year, startTime.Month +            v.Month, startTime.Day + v.Day, startTime.Hour + v.Hour, startTime.Minute + v.Minute, startTime.Millisecond + v.Millisecond);

    return result;
}

This result is wrong... Why ???

You already have the result of the conversion to milliseconds when you do:

TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
DateTime v = new DateTime(time.Ticks); //This is the result

If you want to add the milliseconds to UNIX time, then all you have to do is:

TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
result.Add(time);

If the time isn't in UTC then omit the DateTimeKind.Utc part, but it's generally a good idea to keep the time in UTC and only convert to local time when needed.

private static DateTime FromMS(long microSec)
{
    long milliSec = (long)(microSec / 1000);
    DateTime startTime = new DateTime(1970, 1, 1);

    TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
    return startTime.Add(time);
}

I use this method to convert from a Unix Epoch (with milliseconds) to a DateTime object

private static readonly DateTime UnixEpochStart = 
               DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);


public static DateTime ToDateTimeFromEpoch(this long epochTime)
{
   DateTime result = UnixEpochStart.AddMilliseconds(epochTime);
   return result;
}
long ticks = new DateTime(1970, 1, 1).Ticks;
DateTime dt = new DateTime(ticks);
dt.AddMilliseconds(milliSec);

Try this.

TimeSpan time = TimeSpan.FromMilliseconds(1509359657633);
DateTime date = new DateTime(1970, 1, 1).AddTicks(time.Ticks);

This will convert milliseconds into a correct DateTime.

NOTE:- If you get the milliseconds from JS like Date.now() the millisecond you received here is for UTC. So when you convert to C# DateTime, you will get DateTime in UTC time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM