【问题标题】:get UTC timestamp from today's local time从今天的当地时间获取 UTC 时间戳
【发布时间】:2014-10-18 21:50:43
【问题描述】:

假设我知道这次 (hh:mm:ss) 没有日期,但我知道是今天:

12:34:56

我知道时间在 CST 时区 (UTC +0800)。我需要从时间获取时间戳。

假设当前 UTC 时间是 2014/08/25 17:10:00 并且 CST 是 2014/08/26 01:10:00 (UTC +0800 ) 所以这意味着在 CST 中已经是第二天了。因此我不能使用这样的东西:

var d = new Date().toJSON().slice(0,10);
// "d" returns "2014-08-25" in local time -> this is bad

我需要转换一下:

1:10 (CST) --> 到 2014/08/25 17:10 (UTC) 或其时间戳 1408986600

当我只知道时间和时区时,如何获得完整的日期时间或时间戳?

【问题讨论】:

    标签: javascript timestamp unix-timestamp utc


    【解决方案1】:

    您始终可以直接操作Date 对象的属性:

    var date = new Date();
    
    date.setHours(5);
    date.setMinutes(12);
    date.setSeconds(10);
    
    console.log(date.toUTCString());
    

    【讨论】:

    • 如何“说”它在 CST 而不是本地时间的 Date 对象?我不在 CST,但“1:10”以上的时间是。
    • new Date 是否为您生成正确时区的日期?在 NodeJS 中,它使用您的时区环境变量。在浏览器中,它应该使用您的操作系统设置。我不知道有什么简单的方法可以设置为非本地时区,但是 NodeJS 和浏览器世界中可用的库不同。或者,您始终可以将 UTC 时间戳值移动适当的秒数并重新渲染。
    【解决方案2】:

    我想我找到了使用moment-timezone.js 的简单方法:

    // hh:mm:ss in CST timezone
    var cst_time = '1:10:00'; 
    
    // get today's date in CST timezone
    var cst_today = moment.tz("Asia/Shanghai").format("YYYY-MM-DD"); 
    
    // convert date and time from CST to UTC and format it
    var timestamp = moment(cst_today + " " + cst_time + " +0800").utc().format("YYYY/MM/DD HH:mm:ss");
    
    // returns "2014/08/25 17:10:00" and it is correct
    console.log(timestamp); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-19
      • 2014-11-21
      • 2016-01-19
      • 2020-06-04
      • 2019-11-29
      • 2011-06-14
      • 2018-07-02
      • 2012-02-28
      相关资源
      最近更新 更多