根据时区更改时间基础 momen-timezone。

huangapple go评论67阅读模式
英文:

change time base on timezone momen-timezone

问题

我想将所选的时间转换为用户配置文件中保存的时区,使用 moment-timezone 库。

我的本地系统时区是 PKT(巴基斯坦),用户在他的配置文件中保存的时区是 AEST(澳大利亚/悉尼)。因此,当用户选择时间时,我只希望将该时间转换为用户的时区,并发送到 API。
例如:

const time = "07:00";
const date = "06/13/2023";
const timezone = "Australian/Sydney";
moment(`${date} ${time}`).tz(timezone).format() // 2023-06-20T12:00:00+10:00

转换后的时间应该是上午 7 点 AEST,但库将其转换为中午 12 点。如果我将 moment 默认时区更改为用户配置文件时区,仍然无法获得正确的输出。
例如:

const time = "07:00";
const date = "06/13/2023";
const timezone = "Australian/Sydney";
moment.tz.setDefault(timezone)

moment(`${date} ${time}`).tz(timezone).format() // 2023-06-20T12:00:00+10:00
moment(`${date} ${time}`).format() // 2023-06-20T12:00:00+10:00
moment.tz(`${date} ${time}`, timezone).format() // 2023-06-20T17:00:00+10:00

您可以看到,没有一个输出是我想要实现的。如果 moment 不支持此功能,那么如果您告诉我其他库将会很有帮助。

英文:

i want to convert selected time into timezone saved in user profile using moment-timezone library

my local system timezone is PKT(pakistan) and user has saved timezone in his Profile is AEST(australian/sydney). so when user select time i just want that time in userTimezone and send in API.
e.g

const time  =  "07:00"
const date = "06/13/2023"
const timezone = "Australian/Sydney"
moment(`${date} ${time}`).tz(timezone).format() // 2023-06-20T12:00:00+10:00

converted time should be 7Am AESt but library has convert it into 12pm. if i change moment default timezone into user profile timezone then still i dont get correct output

e.g

const time  =  "07:00"
const date = "06/13/2023"
const timezone = "Australian/Sydney"
 moment.tz.setDefault(timezone)

 moment(`${date} ${time}`).tz(timezone).format() //2023-06-20T12:00:00+10:00
 moment(`${date} ${time}`).format() //2023-06-20T12:00:00+10:00
moment.tz(`${date} ${time}`, timezone).format() // 2023-06-20T17:00:00+10:00

you can see none of the output is what i am trying to acheive. it would be greate if you let me know other library if moment does not support this.

答案1

得分: 0

// 使用以下npm包,"luxon"
// https://moment.github.io/luxon/api-docs/index.html

const { DateTime } = require("luxon");

const yourInputTime = "13:45:21";
const yourDateInput = "2023-06-25";
// 这些输入位于您的时区

// 现在您想要将它们转换成新加坡时区
// 您可以在以下链接中找到所有时区的完整列表
/* https://stackoverflow.com/questions/38399465/how-to-get-list-of-all-timezones-in-javascript/54500197#54500197 */

// 首先构建一个ISO字符串
const yourInputISO = `${yourDateInput}T${yourInputTime}`;
const convertedISO = DateTime.fromISO(yourInputISO).setZone("Asia/Singapore").toISO(); // 2023-06-25T15:45:21.000+08:00

const yourDesiredTime = convertedISO.split("T")[1].split(".")[0] // 15:45:21
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// use the following npm package, &quot;luxon&quot;
// https://moment.github.io/luxon/api-docs/index.html

const { DateTime } = require(&quot;luxon&quot;);

const yourInputTime = &quot;13:45:21&quot;;
const yourDateInput = &quot;2023-06-25&quot;;
// these inputs are in your timezone

// now you want to convert these to let&#39;s day Singapore timezone
// you can find the whole list of timezone from the following link
/* https://stackoverflow.com/questions/38399465/how-to-get-list-of-all-timezones-in-javascript/54500197#54500197 */

// first construct an ISO string
const yourInputISO = `${yourDateInput}T${yourInputTime}`;
const convertedISO = DateTime.fromISO(yourInputISO).setZone(&quot;Asia/Singapore&quot;).toISO(); // 2023-06-25T15:45:21.000+08:00

const yourDesiredTime = convertedISO.split(&quot;T&quot;)[1].split(&quot;.&quot;)[0] // 15:45:21

<!-- end snippet -->

答案2

得分: 0

开始阅读Intl Web/JS API的支持值,然后检查可用的内容 => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf . 列表中返回的任何内容都可以在您的代码/应用程序和浏览器中使用,但可能在其他客户端和浏览器中不起作用。

除非您深入研究时间主题,否则不建议尝试将用户在其个人资料中选择的新位置输入的时间转换为其他地方的时间 - 这可能会很复杂。最好让用户选择一个位置,然后让该位置设置时间,然后保存。计算时间的前后?不需要 - 只需使用Intl API来读取。

话虽如此,请尝试我的代码,不使用外部库:

  1. 用户登录并基于巴基斯坦或其他地方
  2. 用户然后更改时区到新加坡或其他地方 - 这是在代码的这一部分中完成的 let userSelectedCountry = 'Asia/Singapore' ,然后使用Date和RegEx API调用我们的函数来实现我们需要的内容并提取所选(在我们的数组中可用的)时区的正确时间

要使用它,请按照代码注释中的步骤1和2操作。

const event = new Date();
//locales列表 - 不是穷尽无涯的
const localeCodes = ['el', 'en-au', 'en-ca', 'en-gb', 'en-us', 'es-es', 'es-mx', 'it-it'];
//时区列表 - 不是穷尽无涯的
const timeZonesL = ["Africa/Abidjan", "Asia/Aden", "Asia/Almaty", /* ... 省略部分 ... */, "Asia/Yerevan", "Europe/London"];

getDateTime = (country) => { 
  const regexp = new RegExp(`\\b${country}\\b`, 'gi') // 显示如何传递可选标志
  const userTimeZone = timeZonesL.filter(timeZ => timeZ == timeZ.match(country))
  return event.toLocaleString('en-GB', { timeZone: userTimeZone });
  //return event.toLocaleString('en-GB', { timeZone: 'Asia/Singapore' });;
}

//步骤1
//测试1 - 用户登录并选择新的国家/时区后,我们为他们调用它
//例如从下拉菜单中选择
//下拉菜单中的值必须与timeZonesL数组中的某个值匹配
let userSelectedCountry = 'Asia/Singapore'
//构建正则表达式并传递所选的国家
var re = new RegExp("\\b"+userSelectedCountry+"\\b"); 
//如果它测试为regex匹配的真值,我们将使用它作为参数调用我们的函数      
console.log(getDateTime(userSelectedCountry.match(re)))

//步骤2
//在退出登录时,将时间保存为用户选择的时间,例如
//mongoDB.save(getDateTime(userSelectedCountry.match(re)))
//现在我们可以保存用户选择的任何时间
//注意:需要更多工作来完成时区列表,因为某些时区是多余的,某些时区不受某些浏览器支持,您不希望全部都包括
英文:

Start by reading the supported values as part of the Intl Web/JS APi and checking what's available => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf . Anything that's returned in the list you can use in your code/app and browser - but may not work in other clients and browsers.

Unless you dig deep into the topic of time I wouldn't try to convert time that a user has entered from a new location selected in their profile - this could be complicated. Better to let the user pick a location and let the location set the time then save that. Calculation back and off of the time? No need - just use Int API to read from.

That said have a try at my code using no external libraries:

  1. User logs in and is based in Pakistan or wherever
  2. User then changes the timezone to Singapore or somewhere else - this is done in this section of code let userSelectedCountry = &#39;Asia/Singapore&#39; and call our function by using the Date and RegEx APIs to achieve what we need and pull out the correct time for selected (available timezone in our array!) timezone

To use it follow step 1 and 2 in the code comments.

    const event = new Date();
    //list of locales - NOT exhaustive
    const localeCodes = [&#39;el&#39;, &#39;en-au&#39;, &#39;en-ca&#39;, &#39;en-gb&#39;, &#39;en-us&#39;, &#39;es-es&#39;, &#39;es-mx&#39;,&#39;it-it&#39;]
    //list of timezones - NOT exhaustive
    const timeZonesL =   [&quot;Africa/Abidjan&quot;
          , &quot;Asia/Aden&quot;
          , &quot;Asia/Almaty&quot;
          , &quot;Asia/Amman&quot;
          , &quot;Asia/Anadyr&quot;
          , &quot;Asia/Aqtau&quot;
          , &quot;Asia/Aqtobe&quot;
          , &quot;Asia/Ashgabat&quot;
          , &quot;Asia/Ashkhabad&quot;
          , &quot;Asia/Atyrau&quot;
          , &quot;Asia/Baghdad&quot;
          , &quot;Asia/Bahrain&quot;
          , &quot;Asia/Baku&quot;
          , &quot;Asia/Bangkok&quot;
          , &quot;Asia/Barnaul&quot;
          , &quot;Asia/Beirut&quot;
          , &quot;Asia/Bishkek&quot;
          , &quot;Asia/Brunei&quot;
          , &quot;Asia/Calcutta&quot;
          , &quot;Asia/Chita&quot;
          , &quot;Asia/Choibalsan&quot;
          , &quot;Asia/Chongqing&quot;
          , &quot;Asia/Chungking&quot;
          , &quot;Asia/Colombo&quot;
          , &quot;Asia/Dacca&quot;
          , &quot;Asia/Damascus&quot;
          , &quot;Asia/Dhaka&quot;
          , &quot;Asia/Dili&quot;
          , &quot;Asia/Dubai&quot;
          , &quot;Asia/Dushanbe&quot;
          , &quot;Asia/Famagusta&quot;
          , &quot;Asia/Gaza&quot;
          , &quot;Asia/Harbin&quot;
          , &quot;Asia/Hebron&quot;
          , &quot;Asia/Ho_Chi_Minh&quot;
          , &quot;Asia/Hong_Kong&quot;
          , &quot;Asia/Hovd&quot;
          , &quot;Asia/Irkutsk&quot;
          , &quot;Asia/Istanbul&quot;
          , &quot;Asia/Jakarta&quot;
          , &quot;Asia/Jayapura&quot;
          , &quot;Asia/Jerusalem&quot;
          , &quot;Asia/Kabul&quot;
          , &quot;Asia/Kamchatka&quot;
          , &quot;Asia/Karachi&quot;
          , &quot;Asia/Kashgar&quot;
          , &quot;Asia/Kathmandu&quot;
          , &quot;Asia/Katmandu&quot;
          , &quot;Asia/Khandyga&quot;
          , &quot;Asia/Kolkata&quot;
          , &quot;Asia/Krasnoyarsk&quot;
          , &quot;Asia/Kuala_Lumpur&quot;
          , &quot;Asia/Kuching&quot;
          , &quot;Asia/Kuwait&quot;
          , &quot;Asia/Macao&quot;
          , &quot;Asia/Macau&quot;
          , &quot;Asia/Magadan&quot;
          , &quot;Asia/Makassar&quot;
          , &quot;Asia/Manila&quot;
          , &quot;Asia/Muscat&quot;
          , &quot;Asia/Nicosia&quot;
          , &quot;Asia/Novokuznetsk&quot;
          , &quot;Asia/Novosibirsk&quot;
          , &quot;Asia/Omsk&quot;
          , &quot;Asia/Oral&quot;
          , &quot;Asia/Phnom_Penh&quot;
          , &quot;Asia/Pontianak&quot;
          , &quot;Asia/Pyongyang&quot;
          , &quot;Asia/Qatar&quot;
          , &quot;Asia/Qostanay&quot;
          , &quot;Asia/Qyzylorda&quot;
          , &quot;Asia/Rangoon&quot;
          , &quot;Asia/Riyadh&quot;
          , &quot;Asia/Saigon&quot;
          , &quot;Asia/Sakhalin&quot;
          , &quot;Asia/Samarkand&quot;
          , &quot;Asia/Seoul&quot;
          , &quot;Asia/Shanghai&quot;
          , &quot;Asia/Singapore&quot;
          , &quot;Asia/Srednekolymsk&quot;
          , &quot;Asia/Taipei&quot;
          , &quot;Asia/Tashkent&quot;
          , &quot;Asia/Tbilisi&quot;
          , &quot;Asia/Tehran&quot;
          , &quot;Asia/Tel_Aviv&quot;
          , &quot;Asia/Thimbu&quot;
          , &quot;Asia/Thimphu&quot;
          , &quot;Asia/Tokyo&quot;
          , &quot;Asia/Tomsk&quot;
          , &quot;Asia/Ujung_Pandang&quot;
          , &quot;Asia/Ulaanbaatar&quot;
          , &quot;Asia/Ulan_Bator&quot;
          , &quot;Asia/Urumqi&quot;
          , &quot;Asia/Ust-Nera&quot;
          , &quot;Asia/Vientiane&quot;
          , &quot;Asia/Vladivostok&quot;
          , &quot;Asia/Yakutsk&quot;
          , &quot;Asia/Yangon&quot;
          , &quot;Asia/Yekaterinburg&quot;
          , &quot;Asia/Yerevan&quot;
          , &quot;Europe/London&quot;]
    
    getDateTime = (country) =&gt; { 
      const regexp = new RegExp(`\\b${country}\\b`, &#39;gi&#39;) // showing how to pass optional flags
      const userTimeZone = timeZonesL.filter(timeZ =&gt; timeZ == timeZ.match(country))
      return event.toLocaleString(&#39;en-GB&#39;, { timeZone: userTimeZone });
      //return event.toLocaleString(&#39;en-GB&#39;, { timeZone: &#39;Asia/Singapore&#39; });;
    }
    
    //step 1
    //test 1 - after user signs in and selects new country/timezone we call it for them
    //e.g. from a dropdown
    //Value in drop down must match a value in the timeZonesL array
    let userSelectedCountry = &#39;Asia/Singapore&#39;
    //build regex and pass in selected country
    var re = new RegExp(&quot;\\b&quot;+userSelectedCountry+&quot;\\b&quot;); 
    //we then call our function with it as a param if it tests truthy to regex match      
    console.log(getDateTime(userSelectedCountry.match(re)))
    
    //step 2
    //On sign out save the time as to what the user selected e.g. 
    //mongoDB.save(getDateTime(userSelectedCountry.match(re)))
    //now we can save any time the user selects
    //NOTE: more needs to be done to finalise list of timezones as some are redundant, not supported by some
    //browsers and you don&#39;t want all of them

答案3

得分: 0

我无法使用moment-timezone库解决这个问题,所以我转向了dayjs,它解决了我的问题。它正确地将时间转换为所选的时区。以下是这段代码的翻译:

import dayjs from "dayjs";
import utc from "dayjs/plugin/utc"; // 导入 dayjs 的 UTC 插件
import timezone from "dayjs/plugin/timezone";
import customParseFormat from "dayjs/plugin/customParseFormat";

// 使用所需的插件扩展 dayjs
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(customParseFormat);

const getStartAndEndDateTime = (date, time, timezone, duration) => {
  let startDateTime = "";
  let endDateTime = "";

  if (date && time) {
    const formattedDate = dayjs(date).format("YYYY-MM-DD");
    const formattedTime = dayjs(time, "hh:mm a").format("H:mm");
    const timestamp = `${formattedDate} ${formattedTime}`;

    startDateTime = dayjs.tz(timestamp, timezone || dayjs.tz.guess()).format();
    endDateTime = dayjs
      .tz(timestamp, timezone || dayjs.tz.guess())
      .add(duration.value, "m")
      .format();
  }
  return { start_datetime: startDateTime, end_datetime: endDateTime };
};

注意:我已经将引号从 HTML 实体编码 (&quot;) 转换为双引号。

英文:

i could not solve this issue with moment-timezone libarary and so i shift to dayjs it solved my problem. it is correctly converting time in selected timezone. below is the code for this

import dayjs from &quot;dayjs&quot;;
import utc from &quot;dayjs/plugin/utc&quot;; // Import the UTC plugin for dayjs
import timezone from &quot;dayjs/plugin/timezone&quot;;
import customParseFormat from &quot;dayjs/plugin/customParseFormat&quot;;

// Extend dayjs with the required plugins
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(customParseFormat);

const getStartAndEndDateTime = (date, time, timezone, duration) =&gt; {
  let startDateTime = &quot;&quot;;
  let endDateTime = &quot;&quot;;

  if (date &amp;&amp; time) {
    const formateDDate = dayjs(date).format(&quot;YYYY-MM-DD&quot;);
    const formatedTime = dayjs(time, &quot;hh:mm a&quot;).format(&quot;H:mm&quot;);
    const timestamp = `${formateDDate} ${formatedTime}`;

    startDateTime = dayjs.tz(timestamp, timezone || dayjs.tz.guess()).format();
    endDateTime = dayjs
      .tz(timestamp, timezone || dayjs.tz.guess())
      .add(duration.value, &quot;m&quot;)
      .format();
  }
  return { start_datetime: startDateTime, end_datetime: endDateTime };
};

huangapple
  • 本文由 发表于 2023年6月13日 06:12:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定