Calculate day number from an unix-timestamp in a math way?

后端 未结 3 1987
一整个雨季
一整个雨季 2021-01-12 08:13

How can i calculate day number from a unix-timestamp, in a mathematical way and without using any functions and in simple math formula.

1313905026 --> 8 (Today 08/21

3条回答
  •  心在旅途
    2021-01-12 08:25

    t = unix time
    second = t MOD 60  
    minute = INT(t / 60) MOD 60  
    hour = INT(t / 60 / 60) MOD 24  
    days = INT(t / 60 / 60 / 24)  
    years = INT(days / 365.25)  
    year = 1970 + years + 1
    

    1970 started with a Thursday so, we can calculate the day of the week:

    weekday = (days + 4) MOD 7
    

    If Sunday is day 0. If you want Sunday to be day 1 just add 1.

    Now, let's find out how many days we are into the year in question.

    days = days - years * 365 - leapdays
    

    Finally, we find the month and day of the month.

    IF year MOD 4 = 0 THEN ly = 1 ELSE ly = 0
    WHILE month <= 12
        month = month + 1
        IF month = 2 THEN
            DaysInMonth = 28 + NOT(year MOD 4) + NOT(year MOD 100)
                + NOT(year MOD 400)
        ELSE
            DaysInMonth = 30 + (month + (month < 7)) MOD 2
        END IF
        IF days > DaysInMonth THEN days = days - DaysInMonth
    END WHILE
    

    This assumes Boolean values of TRUE = 1, FALSE = 0, NOT TRUE = 0, and NOT FALSE = 1.

    Now we have the year, month, day of the month, hour, minute, and second calculated with adjustments for leap years.

提交回复
热议问题