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();
}
迷茫2017-04-17 14:55:48
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);
}