1

我在 stackoverflow 上读到,将 DateTime 变量转换回 Excel 日期的最简单方法就是:

let exceldate = int(DateTime)

诚然,这是在 c# 而不是 f# 中。这应该可以工作,因为小数代表时间,int 部分代表日期。我试过这个,f# 回来了错误:

The type 'DateTime' does not support a conversion to the type 'int'

那么如何转换回excel日期呢?

更具体地说,我正在尝试为开始日期和结束日期之间的时间段创建第 1 个月的向量。矢量输出和开始日期和结束日期都是浮点数,即excel日期。这是我笨拙的第一次尝试:

let monthlies (std:float) (edd:float)  =
let stddt = System.DateTime.FromOADate std
let edddt = System.DateTime.FromOADate edd
let vecstart = new DateTime(stddt.Year, stddt.Month, 1)
let vecend = new DateTime(edddt.Year, edddt.Month, 1)
let nrmonths = 12 * (edddt.Year-stddt.Year) + edddt.Month - stddt.Month + 1 
let scaler = 1.0 - (float(stddt.Day) - 1.0) / float(DateTime.DaysInMonth(stddt.Year , stddt.Month))
let dtsvec:float[] = Array.zeroCreate nrmonths
dtsvec.[0] <- float(vecstart)
for i=1 to (nrmonths-1)  do
    let temp = System.DateTime.FromOADate dtsvec.[i-1]
    let temp2 =  temp.AddMonths 1
    dtsvec.[i] = float temp2
dtsvec

由于转换问题,这不起作用,而且相当复杂和必要。

我该如何进行转换?我怎样才能更实用地做到这一点?谢谢

4

1 回答 1

1

获得 DateTime 对象后,只需调用 ToOADate,如下所示:

let today = System.DateTime.Now
let excelDate = today.ToOADate()

所以你的例子最终会像这样:

let monthlies (std:float) (edd:float)  =
let stddt = System.DateTime.FromOADate std
let edddt = System.DateTime.FromOADate edd
let vecstart = new System.DateTime(stddt.Year, stddt.Month, 1)
let vecend = new System.DateTime(edddt.Year, edddt.Month, 1)
let nrmonths = 12 * (edddt.Year-stddt.Year) + edddt.Month - stddt.Month + 1 
let scaler = 1.0 - (float(stddt.Day) - 1.0) / float(System.DateTime.DaysInMonth(stddt.Year , stddt.Month))
let dtsvec:float[] = Array.zeroCreate nrmonths
dtsvec.[0] <- vecstart.ToOADate()
for i=1 to (nrmonths-1)  do
    let temp = System.DateTime.FromOADate dtsvec.[i-1]
    let temp2 =  temp.AddMonths 1
    dtsvec.[i] = temp2.ToOADate()
dtsvec

关于摆脱循环,也许是这样的?

type Vector(x: float, y : float) =
   member this.x = x
   member this.y = y

   member this.xDate = System.DateTime.FromOADate(this.x)
   member this.yDate = System.DateTime.FromOADate(this.y)

   member this.differenceDuration = this.yDate - this.xDate
   member this.difference = System.DateTime.Parse(this.differenceDuration.ToString()).ToOADate

type Program() =
    let vector = new Vector(34.0,23.0)
    let difference = vector.difference
于 2013-10-15T11:33:18.120 回答