【问题标题】:Converting Timezones with momentjs and moment-timezone.js使用 momentjs 和 moment-timezone.js 转换时区
【发布时间】:2021-09-07 11:48:04
【问题描述】:

我希望一个人能够有 2 个提示。

  1. 访客时区
  2. 我的时区

我已经有了访客时区。这个想法是转换时区。

客人会选择他的时区,而我的是美国东部标准时间。

我的访客时区正在工作,我无法让它有另一个提示来获取我的时区,并用时刻转换它。

到目前为止,这就是我所拥有的。我希望能够提示其他人保留他们的时区并将访客时区转换为我的时区


// Starts Moment
  var moment = require('moment-timezone');
  
  // Prompt to get the timezone
var prompt = prompt("What timezone") 


// Shows the time in the current timezone

var time = moment().tz(prompt).format();

// Console logs the Time
console.log(time)

// Shows the Current date, and Month
var date = moment().format('dddd'); 
var month = moment().format('MMMM'); 

应该有办法,不过不知道是什么

【问题讨论】:

  • 我不明白您遇到了什么问题。听起来您想做与现在完全相同的事情,但是第二次使用第二组用户输入。如果是这种情况,只需再次提示他们第二个时区并再次运行您的时刻代码。另外,不要使用 prompt 作为变量名 - 将其更改为其他名称 var tz1 = prompt("Guest Timezone"); var tz2 = prompt("My Timezone");
  • 嘿约瑟夫!感谢您的帮助!当我再次提示时,它不起作用!会改变并让您知道!
  • 这可能是因为您在函数中定义了一个名为“prompt”的新变量 - 所以稍后在您的函数中,当您调用“prompt()”时,它会尝试运行您的字符串(这会赢得't work) 而不是本机 window.prompt() 函数。将您的变量声明更改为其他内容 (var tz1 = prompt()) 应该可以解决此问题。
  • 是的,现在可以使用了。谢谢约瑟夫,祝你有美好的一天!
  • 你也是!我会将其发布为答案,以便您可以将问题标记为已关闭。祝你好运!

标签: javascript timezone momentjs


【解决方案1】:

经过一番讨论,问题似乎是由覆盖函数内部的“window.prompt”方法引起的。设置时:

var prompt = prompt("What Timezone")

您正在添加一个名为“prompt”的新变量,当您稍后在代码中使用它时,它将优先于内置的 window.prompt。您应该将变量重命名为更特定于其用途的名称(以及每个变量的唯一名称),如下所示:

// Starts Moment
var moment = require('moment-timezone');

// Prompt to get the timezone
var timezone1 = prompt("Guest Timezone");
var timezone2 = prompt("My Timezone");

// Shows the time in the current timezone
var time1 = moment().tz(timezone1).format();
var time2 = moment().tz(timezone2).format();

// Console logs the Time
console.log(time1);
console.log(time2);

然后,您将有两个格式化的日期字符串(time1 和 time2),每个时区一个。

【讨论】:

    猜你喜欢
    • 2019-01-24
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    相关资源
    最近更新 更多