Convert date between java and .net - 2 days off

前端 未结 3 993
闹比i
闹比i 2021-01-14 17:20

I need to transform a .NET DateTime to an equivalent Java Calendar representation.

The .NET DateTime uses Ticks

3条回答
  •  我在风中等你
    2021-01-14 17:52

    Answering the 'why':

    From the (decompiled - thanks dotPeek!) .NET 4 source code (comments are mine):

    public static DateTime operator -(DateTime d, TimeSpan t)
    {
      //range checks
      long internalTicks = d.InternalTicks;
      long num = t._ticks;
      if (internalTicks < num || internalTicks - 3155378975999999999L > num)
        throw new ArgumentOutOfRangeException("t", 
                Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
    
        else
    
        //plain arithmetic using the Ticks property of the two dates.
        return new DateTime((ulong) (internalTicks - num) | d.InternalKind);
    }
    

    So yeah, absolutely no special 'gregorian' treatment for DateTime operators.

    About the 'how to fix':

    I ended up using something along these lines: (pseudo-Java)

    Calendar cal = new GregorianCalendar();
    cal.set(dt.Year, dt.Month - 1 /*it's 0-based*/, dt.Day, dt.Hour, dt.Minute, dt.Second);
    cal.set(Calendar.MILLISECOND, dt.Millisecond);
    

提交回复
热议问题