Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

c# - What is equivalent of DateTime.ToOADate() in javascript?

How can I get the OADate (OLE Automation date) in javascript? I need to pass my date object (to my web service) in the form of a double value.

in c#:

var d = DateTime.Now.ToOADate();

what is the equivalent in js?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To convert a JScript date to an OLE Automation date, call getVarDate:

http://msdn.microsoft.com/en-us/library/4d4x3w61(VS.85).aspx

(If you go the other way -- that is, you have a JScript object and you assign a property containing a variant of VT_DATE type -- the JScript engine should automatically convert that to the equivalent JScript date.)

If your browser provider did not do you the courtesy of writing a getVarDate method, well, it is not difficult to write the code yourself, but in order to get it right for all cases you have to handle some tricky special cases involving dates before the epoch.

The best way I know of to get the code right is to first convert it to the raw number of whole and fractional days since the epoch, which I note is midnight of December 30, not 31, 1899. Once you have that, you can special-case the before-epoch values.

Be very careful about rounding! I recommend that you round values off to the nearest second before you do the conversion to the OA format. Because the OA format is one where -1.9999999 is just before midnight December 30th 1899, but -2.0 is midnight December 28th, if you round the former to the latter, you just rounded a fraction of a second off into a two-day error.

For the details on the quirks of the OA format, see my article from 2003 on the subject:

http://blogs.msdn.com/b/ericlippert/archive/2003/09/16/53013.aspx

And for an entertaining look at the deeper history of this odd date format, see Joel's article about his Microsoft days:

http://www.joelonsoftware.com/items/2006/06/16.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...