为何Livecode无法将1970年之前的日期转换为秒数?
Livecode无法转换1970年前日期为秒数的原因及解决方法
核心原因
- Livecode的
convert <date> to seconds默认基于Unix时间戳(Epoch时间),该时间戳以1970年1月1日UTC为起始点,1970年之前的日期对应负的秒数。 - 部分旧版Livecode或特定操作系统(如早期Windows)的底层时间API不支持负时间戳,直接触发转换失败。
- 若系统本地时区与UTC存在偏移,1970年1月1日之前的日期可能因时区计算逻辑冲突导致转换异常。
解决方法:手动计算秒数
通过dateItems函数解析日期,再手动实现秒数计算逻辑,绕过底层API限制。示例代码:
on mouseUp put "March 14, 1961" into tDate convert tDate to dateItems put calculateSecondsFromDateItems(tDate) into tSeconds put tSeconds end mouseUp function calculateSecondsFromDateItems pDateItems local tYear, tMonth, tDay, tTotalSeconds put pDateItems[1] into tYear put pDateItems[2] into tMonth put pDateItems[3] into tDay -- 计算1970年到目标年份前一年的总秒数(含闰年) put 0 into tTotalSeconds repeat with y = 1970 down to tYear + 1 if isLeapYear(y) then add 31622400 to tTotalSeconds else add 31536000 to tTotalSeconds end repeat -- 计算目标年份已过月份的秒数 put 0 into tMonthSeconds repeat with m = 1 to tMonth - 1 add daysInMonth(m, tYear) * 86400 to tMonthSeconds end repeat -- 加上当月已过天数的秒数 put (tDay - 1) * 86400 into tDaySeconds -- 计算最终秒数(1970前为负数) put (tMonthSeconds + tDaySeconds) - tTotalSeconds into tTotalSeconds -- 叠加时分秒数值 add pDateItems[4] * 3600 to tTotalSeconds add pDateItems[5] * 60 to tTotalSeconds add pDateItems[6] to tTotalSeconds return tTotalSeconds end calculateSecondsFromDateItems function isLeapYear pYear if pYear mod 400 = 0 then return true if pYear mod 100 = 0 then return false if pYear mod 4 = 0 then return true return false end isLeapYear function daysInMonth pMonth, pYear switch pMonth case 1,3,5,7,8,10,12: return 31 case 4,6,9,11: return 30 case 2: return isLeapYear(pYear) ? 29 : 28 end switch end daysInMonth
这段代码完全手动处理日期到秒数的转换逻辑,不依赖系统底层时间API,可稳定支持1970年之前的日期转换。
内容的提问来源于stack exchange,提问作者Eduardo Volpi de Almeida
相关产品推荐
相关产品推荐

