javascript的Date日期文本与.net的DateTime之间互转
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
string fmtDate = "ddd MMM d HH:mm:ss 'UTC'zz'00' yyyy";
CultureInfo ciDate = CultureInfo.CreateSpecificCulture("en-US");
string 得到js格式的时间文本 = DateTime.Now.ToString(fmtDate, ciDate);
DateTime 从js时间文本里得DateTime = DateTime.ParseExact(
"Wed Apr 7 14:40:41 UTC+0800 2010", fmtDate, ciDate);
Console.WriteLine(得到js格式的时间文本);
Console.WriteLine(从js时间文本里得DateTime);
CultureInfo ciDate = CultureInfo.CreateSpecificCulture("en-US");
string 得到js格式的时间文本 = DateTime.Now.ToString(fmtDate, ciDate);
DateTime 从js时间文本里得DateTime = DateTime.ParseExact(
"Wed Apr 7 14:40:41 UTC+0800 2010", fmtDate, ciDate);
Console.WriteLine(得到js格式的时间文本);
Console.WriteLine(从js时间文本里得DateTime);
再记录一些 DateTime 的相关知识
DateTime.ToBinary 的实现原理:如果是 UTC 时刻,则取 Ticks 然后通过以下运算得到。
long binaryValue = DateTime.UtcNow.Ticks | (((long) 1) << 0x3e);
DateTime.Ticks 则是 从公元 1-1-1 0:00:00 起过去的时间,以 100 nanosecond(100纳秒,10-7 秒)为一个刻度。
如果是类似java之类的从 epoch (就是 1970-01-01 00:00:00.000 )起算的,则要对这个数值做相应的运算
//
const long t1970 = 0x89F7FF5F7B58000L;
const long t1970 = 0x89F7FF5F7B58000L;
DateTime epoch = DateTime.FromBinary(t1970);
long javams = (DateTime.UtcNow.Ticks - t1970) / 10000L;
//long mm = java.util.Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis()
//(javams == mm) = true
//
同理,要在.net里得到像 javascript 一样的时间值 new Date().getTime() 的值。则是
long jsNow = (DateTime.UtcNow.Ticks - 0x89F7FF5F7B58000L) / 10000L;
如果需要从java实现 .net 的 DateTime.Now.ToBinary(),则如下
//
static long t1970 = 0x89F7FF5F7B58000L;
long mm = java.util.Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis() * 10000 + t1970;
long binaryValue = mm | (((long) 1) << 0x3e);
System.out.println(binaryValue);
//
long mm = java.util.Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis() * 10000 + t1970;
long binaryValue = mm | (((long) 1) << 0x3e);
System.out.println(binaryValue);
//