Need a formula: Extracting Years from Seconds Since January 1, 0001 12:00 AM

后端 未结 7 467
春和景丽
春和景丽 2021-01-12 05:22

Input: # of seconds since January 1st, of Year 0001

Output: # of Full years during this time period

I have developed an algorithm that I do not think is the

相关标签:
7条回答
  • 2021-01-12 06:14

    I know this question is old now, but I see ones like it often and there weren't any easy answers in here.

    My solution uses an old trick of writing two dates as if they were numbers (e.g. 'Dec 12th 2013' as 20131212) and then subtracting one from the other and discarding the last four digits. I dug up my implementation in F#, you can paste it into LinqPad to check answers. Takes leap years etc into account too:

    let dateFrom = new DateTime(1,1,1)
    
    let dateTo = dateFrom.AddSeconds(100000000.0)
    
    let yearsSince dateFrom dateTo =
        let intRepresentation (date: DateTime) = 
            date.ToString "yyyy.MMdd" |> Convert.ToDouble
    
        let dateToNum = intRepresentation dateTo
        let dateFromNum = intRepresentation dateFrom
    
        int (dateToNum - dateFromNum)
    
    yearsSince dateFrom dateTo |> Dump
    
    let dob = DateTime(1985, 4, 16)
    
    let calculateAge = yearsSince dob
    
    calculateAge DateTime.Today |> Dump
    

    Please note that this is quite naive: it doesn't take timezones or historical timezone changes into account beyond those that are already handled by .NET's DateTime class. The actual grunt work is being done by the DateTime.AddSeconds method. Hope this helps.

    0 讨论(0)
提交回复
热议问题