英文:
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: 'long', month: 'long',day: 'numeric'})
var creation_time= myData.current_weather && 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: '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;
}
<!-- end snippet -->
Hope you find this answer usefull.
Have a great day!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论