日期时间转换为Excel中的日期f#

时间:2013-10-15 11:28:14

标签: f#

我在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

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

如何进行转换?我怎样才能在功能上做到这一点?感谢

1 个答案:

答案 0 :(得分: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