asp.net - java calendar类的如下操作 在.net c#中要怎么实现?
大家讲道理
大家讲道理 2017-04-17 14:53:48
0
1
940

Java has Calendar Class, but C# doesn't. How to implement the below Java function in C#?

//获得从昨天开始的时间 in Java
    public static long yesterdayBeginTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(1)
迷茫

Already answered you in your other post http://segmentfault.com/q/1010000003707587

The main reason is that the time representation of C# and Java is a little different

  • C# uses Tick (100 nanoseconds), Java uses milliseconds.

  • C# starts from 0001-1-1, Java starts from 1970-1-1

So conversion is required. The following two conversion methods are codes copied from Viti.Util

        /// <summary>
        /// 计算从1970年1月1日到指定日期的毫秒数数,与 Java 中 <c>java.util.Date.getTime()</c> 返回的值相同。
        /// </summary>
        /// <param name="value"></param>
        /// <param name="timezone"></param>
        /// <returns></returns>
        public static long ToJavaMilliseconds(this DateTime value, TimeZoneInfo timezone = null)
        {
            DateTime date1970 = new DateTime(1970, 1, 1, 0, 0, 0);
            date1970 = TimeZoneInfo.ConvertTimeFromUtc(date1970, timezone ?? TimeZoneInfo.Local);
            return (value.Ticks - date1970.Ticks) / 10000;
        }

        /// <summary>
        /// 根据 Java 中表示时间和 <c>long</c> 型数据,恢复成 <see cref="DateTime" /> 类型数据。
        /// </summary>
        /// <param name="value"></param>
        /// <param name="timezone"></param>
        /// <returns></returns>
        public static DateTime FromJavaMilliseconds(long value, TimeZoneInfo timezone = null)
        {
            DateTime date1970 = TimeZoneInfo.ConvertTimeFromUtc(
                new DateTime(1970, 1, 1), timezone ?? TimeZoneInfo.Local);
            return new DateTime(date1970.Ticks + value * 10000);
        }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template