V
V
Vlad Zaitsev2016-08-20 01:03:28
Programming
Vlad Zaitsev, 2016-08-20 01:03:28

Algorithm to convert date to Unix-time?

What is the algorithm for translating a human-readable date into epoch?
I found the reverse conversion: How to display the date from unixtime (algorithm?)
And how to convert it to unix-time?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad Zaitsev, 2016-08-20
@vvzvlad

Traditionally, "he asked, he answered." True, lua, but easy to read.
UPD: if minute < 1 then return nil end is powerful. corrected.

function app_rtc_date2epoch(year,month,day,hour,minute,second)
    local leap = 0

    local t_month = {0,31,59,90,120,151,181,212,243,273,304,334}
    local t_leapyear = {72,76,80,84,88,92,96,00,04,08,12,16,20,24,28,32,36}
    local sum_year = 0

    function get_leapyear(year)
       for key,value in pairs(t_leapyear) do
          if (value + 1900) == year then return 1 end
       end   
       for key,value in pairs(t_leapyear) do
          if (value + 2000) == year then return 1 end
       end   
    return nil
    end
    if year < 1970 or year > 2038 then
       return nil
    elseif month < 1 or month > 12 then
       return nil
    elseif hour < 0 or hour > 23 then
       return nil
    elseif minute < 0 or minute > 59 then
       return nil
    elseif second < 0 or second > 59 then
       return nil
    end
    if day > 28 and get_leapyear(year) == nil then
       return nil
    end
    if day > 29 then return nil end
    for y = 1971,year do
       sum_year = sum_year + 31536000
    if    get_leapyear(y) ~= nil then sum_year = sum_year + 86400 end
    end
    sum_month = (t_month[month]*86400)
    tsp = sum_year + sum_month + ((day-1)*86400) + hour*3600 + minute*60 + second
    return tsp
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question