英文:
How can i convert time to unix timestamp?
问题
以下是您提供的代码的翻译部分:
// 我有一个 twelvedata API,用它获取数据到 lightweightchart。我使用 getTime() 将时间转换为 Unix 时间戳,但图表仍然不起作用。
// 错误:
Uncaught Error: 值为空
// 代码:
var intervals = ['15分钟', '1天', '1周', '1个月'];
const apiKey = '我的API密钥';
async function fetchData(interval) {
const now = new Date();
let startDate, endDate;
if (interval === '15分钟') {
// 获取过去 14 天的数据
endDate = now.toISOString().split('T')[0];
startDate = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
} else if (interval === '1天') {
// 获取过去 6 周的数据
endDate = now.toISOString().split('T')[0];
startDate = new Date(now.getTime() - 6 * 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
} else if (interval === '1周') {
// 获取过去 12 个月的数据
endDate = now.toISOString().split('T')[0];
startDate = new Date(now.getTime() - 12 * 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
} else if (interval === '1个月') {
// 获取过去 3 年的数据
endDate = now.toISOString().split('T')[0];
startDate = new Date(now.getTime() - 3 * 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
}
const url = `https://api.twelvedata.com/time_series?symbol=AAPL&interval=${interval}&apikey=${apiKey}&start_date=${startDate}&end_date=${endDate}&format=JSON&timezone=utc`;
const response = await fetch(url);
const data = await response.json();
console.log(data);
const values = data.values || [];
return values.map(d => {
return {
time: new Date(d.datetime).getTime(),
open: Number(d.open),
high: Number(d.high),
low: Number(d.low),
close: Number(d.close)
};
});
}
// let candlestickSeries;
let candlestickSeries;
async function syncToInterval(interval) {
const data = await fetchData(interval);
console.log('间隔的数据:', interval);
console.log(data);
if (candlestickSeries) {
chart.removeSeries(candlestickSeries);
}
candlestickSeries = chart.addCandlestickSeries({
upColor: '#4caf50',
downColor: '#ef5350',
borderVisible: false
});
candlestickSeries.setData(data);
}
// 初始加载
syncToInterval(intervals[0]);
var switcherElement = createSimpleSwitcher(intervals, intervals[0], syncToInterval);
var chartElement = document.createElement('div');
var chart = LightweightCharts.createChart(chartElement, {
width: 900,
height: 600,
layout: {
background: {
type: 'solid',
color: '#000000',
},
textColor: '#d1d4dc',
},
grid: {
vertLines: {
visible: false,
},
horzLines: {
color: 'rgba(42, 46, 57, 0.5)',
},
},
rightPriceScale: {
borderVisible: false,
},
timeScale: {
borderVisible: false,
},
crosshair: {
horzLine: {
visible: false,
},
},
});
const currentLocale = window.navigator.languages[0];
const myPriceFormatter = Intl.NumberFormat(currentLocale, {
style: "currency",
currency: "USD", // 数据点的货币
}).format;
chart.applyOptions({
localization: {
priceFormatter: myPriceFormatter,
},
});
document.body.appendChild(chartElement);
document.body.appendChild(switcherElement);
请注意,代码中的翻译是根据原文的上下文猜测的,某些术语可能需要根据实际情况进行微调。如果您需要进一步的帮助或有任何问题,请随时提出。
英文:
I have a twelvedata api, where i get my data to the lightweightchart. I convert the time to unix timestamp with getTime(), but the chart is still not working.
Error:
Uncaught Error: Value is null
The code:
var intervals = ['15min', '1day', '1week', '1month'];
const apiKey = 'myapikey';
async function fetchData(interval) {
const now = new Date();
let startDate, endDate;
if (interval === '15min') {
// fetch last 14 days of data
endDate = now.toISOString().split('T')[0];
startDate = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
} else if (interval === '1day') {
// fetch last 6 weeks of data
endDate = now.toISOString().split('T')[0];
startDate = new Date(now.getTime() - 6 * 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
} else if (interval === '1week') {
// fetch last 12 months of data
endDate = now.toISOString().split('T')[0];
startDate = new Date(now.getTime() - 12 * 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
} else if (interval === '1month') {
// fetch last 3 years of data
endDate = now.toISOString().split('T')[0];
startDate = new Date(now.getTime() - 3 * 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
}
const url = `https://api.twelvedata.com/time_series?symbol=AAPL&interval=${interval}&apikey=${apiKey}&start_date=${startDate}&end_date=${endDate}&format=JSON&timezone=utc`;
const response = await fetch(url);
const data = await response.json();
console.log(data);
const values = data.values || [];
return values.map(d => {
return {
time: new Date(d.datetime).getTime(),
open: Number(d.open),
high: Number(d.high),
low: Number(d.low),
close: Number(d.close)
};
});
}
// let candlestickSeries;
let candlestickSeries;
async function syncToInterval(interval) {
const data = await fetchData(interval);
console.log('data for interval:', interval);
console.log(data);
if (candlestickSeries) {
chart.removeSeries(candlestickSeries);
}
candlestickSeries = chart.addCandlestickSeries({
upColor: '#4caf50',
downColor: '#ef5350',
borderVisible: false
});
candlestickSeries.setData(data);
}
// initial load
syncToInterval(intervals[0]);
var switcherElement = createSimpleSwitcher(intervals, intervals[0], syncToInterval);
var chartElement = document.createElement('div');
var chart = LightweightCharts.createChart(chartElement, {
width: 900,
height: 600,
layout: {
background: {
type: 'solid',
color: '#000000',
},
textColor: '#d1d4dc',
},
grid: {
vertLines: {
visible: false,
},
horzLines: {
color: 'rgba(42, 46, 57, 0.5)',
},
},
rightPriceScale: {
borderVisible: false,
},
timeScale: {
borderVisible: false,
},
crosshair: {
horzLine: {
visible: false,
},
},
});
const currentLocale = window.navigator.languages[0];
const myPriceFormatter = Intl.NumberFormat(currentLocale, {
style: "currency",
currency: "USD", // Currency for data points
}).format;
chart.applyOptions({
localization: {
priceFormatter: myPriceFormatter,
},
});
document.body.appendChild(chartElement);
document.body.appendChild(switcherElement);
I tryed deleting the getTime(), and in the chart there showed up one bar. I tryed to make a breakdown to hour,minute,second and then convert to unix timestamp but that not worked to.
答案1
得分: 1
如果您想使用时间戳,请将 time 属性定义为 UNIX 时间戳。这与原生 JS Date 对象返回的值不同。基本上,您需要将这个数字除以 1000。
(https://tradingview.github.io/lightweight-charts/docs/api#utctimestamp)
英文:
If you want to use a timestamp, then the time property should be defined as a UNIX timestamp. This is different to the value you get from the native JS Date object. Essentially you would need to divide the number by 1000.
(https://tradingview.github.io/lightweight-charts/docs/api#utctimestamp)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论