如何解决此错误 Uncaught RangeError: 无效的时间值错误

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

How to resolve this error Uncaught RangeError: Invalid time value error

问题

以下是我的代码。我正在尝试从openmeteo API中获取当前天气时间并在HTML元素中使用它,但即使添加了检查,仍然出现此错误。

const DAY_FORMATTER = new Intl.DateTimeFormat(undefined, { weekday: 'long', month: 'long', day: 'numeric' });
var creation_time = myData.current_weather && myData.current_weather.time;
var currentdate = DAY_FORMATTER.format(creation_time * 1000);
英文:

Below is my code. I am trying to access current weather time from openmeteo API and use it in html elment, but getting this error even after adding the check.

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

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

const DAY_FORMATTER =  new Intl.DateTimeFormat(undefined, { weekday: &#39;long&#39;, month: &#39;long&#39;,day: &#39;numeric&#39;})
    var creation_time= myData.current_weather &amp;&amp; myData.current_weather.time
  var currentdate = DAY_FORMATTER.format(creation_time*1000)

<!-- end snippet -->

答案1

得分: 1

我认为你面临的问题是creation_time变量是一个布尔值,计算不正确。因此,为了检查对象内的属性是否存在,我添加了可选链,它将返回未定义而不会引发错误。

const DAY_FORMATTER = new Intl.DateTimeFormat(undefined, { weekday: 'long', month: 'long', day: 'numeric' });
let creationTime = myData?.current_weather?.time;

if (creationTime){
  let currentDate = DAY_FORMATTER.format(creationTime*1000);
  document.getElementById('demo').innerHTML = currentDate;
}

希望你找到这个答案有用。

祝你有一个美好的一天!

英文:

I think the problem you are facing is that creation_time variable is a boolean and the calculation doesn't add up. So to check if attribute inside object exists, I have added optional chaining that will just throw undefined and won't throw an error.

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

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

const DAY_FORMATTER =  new Intl.DateTimeFormat(undefined, { weekday: &#39;long&#39;, month: &#39;long&#39;,day: &#39;numeric&#39;})
let creationTime = myData?.current_weather?.time;

if (creationTime){
  let currentDate = DAY_FORMATTER.format(creationTime*1000);
  document.getElementById(&#39;demo&#39;).innerHTML = currentDate;
}

<!-- end snippet -->

Hope you find this answer usefull.

Have a great day!

huangapple
  • 本文由 发表于 2023年7月13日 15:13:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76676796.html
匿名

发表评论

匿名网友

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

确定