【问题标题】:How to convert from date to unix_timestamp using javascript如何使用 javascript 将日期转换为 unix_timestamp
【发布时间】:2012-04-04 13:27:19
【问题描述】:

我有一个时间字符串,格式如下YYYY-MM-DD hh:mm:ss

我想将其转换为使用 Javascript 将日期字符串传递给 mysql unix_timestamp 函数的等效项。

我尝试解析日期并将其传递给Date.UTC() 函数,但它似乎给了我与我想要的不同的时间。帮助。

【问题讨论】:

    标签: javascript mysql date timestamp unix-timestamp


    【解决方案1】:

    Convert a Unix timestamp to time in JavaScript已经解决了问题...

    // create a new javascript Date object based on the timestamp 
    // multiplied by 1000 so that the argument is in milliseconds, not seconds 
    var date = new Date(unix_timestamp*1000); 
    // hours part from the timestamp 
    var hours = date.getHours(); 
    // minutes part from the timestamp 
    var minutes = date.getMinutes(); 
    // seconds part from the timestamp 
    var seconds = date.getSeconds(); 
    
    // will display time in 10:30:23 format 
    var formattedTime = hours + ':' + minutes + ':' + seconds; 
    

    【讨论】:

    • 我正在寻找另一种方式
    【解决方案2】:

    不确定这是否会有所帮助。但请记住,您可以在 MySQL 中使用 UNIX_TIMESTAMP(DateTime) 函数来执行此操作。您还可以通过其他方式将 unix 时间戳转换为 DateTimes:FROM_UNIXTIME(UnixTimestamp)

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      您是否尝试过构建日期对象然后使用 .getTime()?这可能就是你想要的。

      例如:Math.round(new Date('2012-03-19 21:01:54').getTime() / 1000)

      【讨论】:

        【解决方案4】:

        如果您提供 UTC 时间戳,并且想要自 1970 年 1 月 1 日以来的秒数,则:

        [...]

        编辑

        重温了我原来的答案,不喜欢,以下更好:

        // Given an ISO8601 UTC timestamp, or one formatted per the OP,
        // return the time in seconds since 1970-01-01T00:00:00Z
        function toSecondsSinceEpoch(s) {
          s = s.split(/[-A-Z :\.]/i);
          var d = new Date(Date.UTC(s[0], --s[1], s[2], s[3], s[4], s[5]));
          return Math.round(d.getTime()/1000);
        }
        

        请注意,OP 中的字符串不符合 ISO8601,但上面的内容可以使用它。如果时间戳在本地时区,则:

        // Given an ISO8601 timestamp in the local timezone, or one formatted per the OP,
        // return the time in seconds since 1970-01-01T00:00:00Z
        function toSecondsSinceEpochLocal(s) {
          s = s.split(/[-A-Z :\.]/i);
          var d = new Date(s[0],--s[1],s[2],s[3],s[4],s[5]);
          return Math.round(d.getTime()/1000);
        }
        

        如果要容纳小数秒,则需要多花一点力气将小数部分转换为毫秒。

        【讨论】:

        • 小注:对于修改后的答案,将Date.UTC的结果传递给Date构造函数并调用getTime是不必要的——Date.UTC直接返回一个数字时间戳:return Math.round(Date.UTC(s[0], s[1], s[2], s[3], s[4], s[5], s[6]) / 1000);加上Function.prototype.apply 和按位运算的地板(你可能应该是地板而不是四舍五入),你得到return (Date.UTC.apply(Date, s) / 1000) | 0;
        • @distilledchaos——你不能像这样使用 apply 因为第二个参数需要递减。
        • 哇,该死。你说得对。我可能有点过火了。
        猜你喜欢
        • 1970-01-01
        • 2017-01-10
        • 1970-01-01
        • 1970-01-01
        • 2017-04-15
        • 2020-03-19
        • 2019-06-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多