You must be aware of the .NET method "DateTime.FromOADate(double d)". I need to implement the same functionality in javascript. i.e given a double value like "40967.6424503935" it has to be converted to "2/28/2012 3:25:07 PM" Can someone please help me out?
Thanks in advance!
You must be aware of the .NET method "DateTime.FromOADate(double d)". I need to implement the same functionality in javascript. i.e given a double value like "40967.6424503935" it has to be converted to "2/28/2012 3:25:07 PM" Can someone please help me out?
Thanks in advance!
Share Improve this question asked May 4, 2012 at 5:49 semantic_c0d3rsemantic_c0d3r 8012 gold badges15 silver badges33 bronze badges3 Answers
Reset to default 14The automation date is the number of days since January 1, 1900 (with the year 1900 strangely being treated as a leap year). So a conversion is:
var oaDate = 40967.6424503935;
var date = new Date();
date.setTime((oaDate - 25569) * 24 * 3600 * 1000);
alert(date);
This solution creates a UTC date. When you display it, it'll be displayed in your local timezone. Depending on whether your date is a local date or a UTC date, this is correct or will require some additional timezone fiddling.
As @donovan shares, it is actually from 12/30/1899 .net function documentation
An OLE Automation date is implemented as a floating-point number whose integral component is the number of days before or after midnight, 30 December 1899, and whose fractional component represents the time on that day divided by 24. For example, midnight, 31 December 1899 is represented by 1.0; 6 A.M., 1 January 1900 is represented by 2.25; midnight, 29 December 1899 is represented by -1.0; and 6 A.M., 29 December 1899 is represented by -1.25.
I think this is a simple solution as well (you can easily collapse it into a single line.):
// distance from ole to epoch in milliseconds.
// We need to invert sign later (bc it is before epoch!)
const oleToEpoch = new Date("12/30/1899")).getTime()
// distance from ole to target (our number
const oleToTarget = 40967.6424503935*24*60*60*1000
// + because of sign change
const resultInMs = oleToTarget + oleToEpoch
// useIndia timezone
console.log(new Date(resultInMs).toLocaleString("en-IN"))
// distance from ole to epoc in milliseconds
const oleToEpoch = new Date("12/30/1899").getTime()
const oleToTarget = 40967.6424503935*24*60*60*1000
// + because of sign change
const resultInMs = oleToTarget + oleToEpoch
console.log(new Date(resultInMs).toLocaleString("en-IN"))
I've made it into a little function:
// distance from ole to epoc in milliseconds
function oleToDate(ole, timezone) {
const oleToEpoch = new Date("12/30/1899").getTime()
const oleToTarget = ole * 24 * 60 * 60 * 1000
// + because of sign change
const resultInMs = oleToTarget + oleToEpoch
const result = new Date(resultInMs)
if (timezone) {
return result.toLocaleString(timezone)
}
return result
}