c# DateTime时间格式和JAVA时间戳格式相互转换

https://www.cnblogs.com/ZCoding/p/4192067.html

/// java时间戳格式时间戳转为C#格式时间  
public static DateTime GetTime(long timeStamp)
{
    DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
    long lTime = timeStamp * 10000;
    TimeSpan toNow = new TimeSpan(lTime);
    return dtStart.Add(toNow);
}

/// C# DateTime时间格式转换为Java时间戳格式  
public static long ConvertDateTime(System.DateTime time)
{
    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
    return (long)(time - startTime).TotalMilliseconds;
}

https://www.cnblogs.com/Donnnnnn/p/6088217.html

封装一下,可直接用。

以后碰到java的long time,直接使用DateTime dt=ConvertJavaDateTimeToNetTime(1207969641193);这样使用即可。

这串日期数字:java长整型日期,毫秒为单位 

复制代码
public static DateTime convertJavaLongtimeToDatetime(long time_JAVA_Long)  
{            
    DateTime dt_1970 = new DateTime(1970, 1, 1, 0, 0, 0);        //年月日时分秒
    long tricks_1970 = dt_1970.Ticks;                           //1970年1月1日刻度                         
    long time_tricks = tricks_1970 + time_JAVA_Long * 10000;    //日志日期刻度                         
    DateTime dt = new DateTime(time_tricks).AddHours(8);        //+8小时,转化为DateTime
    return dt;
}
复制代码

   在计算机中,时间实际上是用数字表示的。我们把1970年1月1日 00:00:00 UTC+00:00时区的时刻称为epoch time,记为0(1970年以前的时间timestamp为负数),当前时间就是相对于epoch time的秒数,称为timestamp。

  Java统计从1970年1月1日起的毫秒的数量表示日期。也就是说,例如,1970年1月2日,是在1月1日后的86,400,000毫秒。同样的,1969年12月31日是在1970年1月1日前86,400,000毫秒。Java的Date类使用long类型纪录这些毫秒值.因为long是有符号整数,所以日期可以在1970年1月1日之前,也可以在这之后。Long类型表示的最大正值和最大负值可以轻松的表示290,000,000年的时间,这适合大多数人的时间要求。
     Java中可以用System.currentTimeMillis() 获取当前时间的long形式,它的标示形式是从1970年1月1日起的到当前的毫秒的数。

   C# 日期型数据的长整型值是自 0001 年 1 月 1 日午夜 12:00,以来所经过时间以100 毫微秒为间隔表示时的数字。这个数在 C# 的 DateTime 中被称为Ticks(刻度)。DateTime 类型有一个名为 Ticks 的长整型只读属性,就保存着这个值。
     .NET下计算时间的方式不太一样,它是计算单位是Ticks,这里就需要做一个C#时间转换。关于Ticks,msdn上是这样说的: 
A single tick represents one hundred nanoseconds or one ten-millionth of a second. The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001. 
就是从公元元年元月1日午夜到指定时间的千万分之一秒了,为了和Java比较,说成万分之一毫秒。 

 需要注意的是,因为我们在东八区,所以要加8个小时。 

参考:

http://blog.csdn.net/dragonpeng2008/article/details/8681435

原文地址:https://www.cnblogs.com/kelelipeng/p/14067506.html