如何将时间转换为Unix时间戳?

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

How can i convert time to unix timestamp?

问题

以下是您提供的代码的翻译部分:

  1. // 我有一个 twelvedata API,用它获取数据到 lightweightchart。我使用 getTime() 将时间转换为 Unix 时间戳,但图表仍然不起作用。
  2. // 错误:

Uncaught Error: 值为空

  1. // 代码:
  2. var intervals = ['15分钟', '1天', '1周', '1个月'];
  3. const apiKey = '我的API密钥';
  4. async function fetchData(interval) {
  5. const now = new Date();
  6. let startDate, endDate;
  7. if (interval === '15分钟') {
  8. // 获取过去 14 天的数据
  9. endDate = now.toISOString().split('T')[0];
  10. startDate = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
  11. } else if (interval === '1天') {
  12. // 获取过去 6 周的数据
  13. endDate = now.toISOString().split('T')[0];
  14. startDate = new Date(now.getTime() - 6 * 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
  15. } else if (interval === '1周') {
  16. // 获取过去 12 个月的数据
  17. endDate = now.toISOString().split('T')[0];
  18. startDate = new Date(now.getTime() - 12 * 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
  19. } else if (interval === '1个月') {
  20. // 获取过去 3 年的数据
  21. endDate = now.toISOString().split('T')[0];
  22. startDate = new Date(now.getTime() - 3 * 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
  23. }
  24. const url = `https://api.twelvedata.com/time_series?symbol=AAPL&interval=${interval}&apikey=${apiKey}&start_date=${startDate}&end_date=${endDate}&format=JSON&timezone=utc`;
  25. const response = await fetch(url);
  26. const data = await response.json();
  27. console.log(data);
  28. const values = data.values || [];
  29. return values.map(d => {
  30. return {
  31. time: new Date(d.datetime).getTime(),
  32. open: Number(d.open),
  33. high: Number(d.high),
  34. low: Number(d.low),
  35. close: Number(d.close)
  36. };
  37. });
  38. }
  39. // let candlestickSeries;
  40. let candlestickSeries;
  41. async function syncToInterval(interval) {
  42. const data = await fetchData(interval);
  43. console.log('间隔的数据:', interval);
  44. console.log(data);
  45. if (candlestickSeries) {
  46. chart.removeSeries(candlestickSeries);
  47. }
  48. candlestickSeries = chart.addCandlestickSeries({
  49. upColor: '#4caf50',
  50. downColor: '#ef5350',
  51. borderVisible: false
  52. });
  53. candlestickSeries.setData(data);
  54. }
  55. // 初始加载
  56. syncToInterval(intervals[0]);
  57. var switcherElement = createSimpleSwitcher(intervals, intervals[0], syncToInterval);
  58. var chartElement = document.createElement('div');
  59. var chart = LightweightCharts.createChart(chartElement, {
  60. width: 900,
  61. height: 600,
  62. layout: {
  63. background: {
  64. type: 'solid',
  65. color: '#000000',
  66. },
  67. textColor: '#d1d4dc',
  68. },
  69. grid: {
  70. vertLines: {
  71. visible: false,
  72. },
  73. horzLines: {
  74. color: 'rgba(42, 46, 57, 0.5)',
  75. },
  76. },
  77. rightPriceScale: {
  78. borderVisible: false,
  79. },
  80. timeScale: {
  81. borderVisible: false,
  82. },
  83. crosshair: {
  84. horzLine: {
  85. visible: false,
  86. },
  87. },
  88. });
  89. const currentLocale = window.navigator.languages[0];
  90. const myPriceFormatter = Intl.NumberFormat(currentLocale, {
  91. style: "currency",
  92. currency: "USD", // 数据点的货币
  93. }).format;
  94. chart.applyOptions({
  95. localization: {
  96. priceFormatter: myPriceFormatter,
  97. },
  98. });
  99. document.body.appendChild(chartElement);
  100. 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:

  1. Uncaught Error: Value is null

The code:

  1. var intervals = ['15min', '1day', '1week', '1month'];
  2. const apiKey = 'myapikey';
  3. async function fetchData(interval) {
  4. const now = new Date();
  5. let startDate, endDate;
  6. if (interval === '15min') {
  7. // fetch last 14 days of data
  8. endDate = now.toISOString().split('T')[0];
  9. startDate = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
  10. } else if (interval === '1day') {
  11. // fetch last 6 weeks of data
  12. endDate = now.toISOString().split('T')[0];
  13. startDate = new Date(now.getTime() - 6 * 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
  14. } else if (interval === '1week') {
  15. // fetch last 12 months of data
  16. endDate = now.toISOString().split('T')[0];
  17. startDate = new Date(now.getTime() - 12 * 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
  18. } else if (interval === '1month') {
  19. // fetch last 3 years of data
  20. endDate = now.toISOString().split('T')[0];
  21. startDate = new Date(now.getTime() - 3 * 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
  22. }
  23. const url = `https://api.twelvedata.com/time_series?symbol=AAPL&interval=${interval}&apikey=${apiKey}&start_date=${startDate}&end_date=${endDate}&format=JSON&timezone=utc`;
  24. const response = await fetch(url);
  25. const data = await response.json();
  26. console.log(data);
  27. const values = data.values || [];
  28. return values.map(d => {
  29. return {
  30. time: new Date(d.datetime).getTime(),
  31. open: Number(d.open),
  32. high: Number(d.high),
  33. low: Number(d.low),
  34. close: Number(d.close)
  35. };
  36. });
  37. }
  38. // let candlestickSeries;
  39. let candlestickSeries;
  40. async function syncToInterval(interval) {
  41. const data = await fetchData(interval);
  42. console.log('data for interval:', interval);
  43. console.log(data);
  44. if (candlestickSeries) {
  45. chart.removeSeries(candlestickSeries);
  46. }
  47. candlestickSeries = chart.addCandlestickSeries({
  48. upColor: '#4caf50',
  49. downColor: '#ef5350',
  50. borderVisible: false
  51. });
  52. candlestickSeries.setData(data);
  53. }
  54. // initial load
  55. syncToInterval(intervals[0]);
  56. var switcherElement = createSimpleSwitcher(intervals, intervals[0], syncToInterval);
  57. var chartElement = document.createElement('div');
  58. var chart = LightweightCharts.createChart(chartElement, {
  59. width: 900,
  60. height: 600,
  61. layout: {
  62. background: {
  63. type: 'solid',
  64. color: '#000000',
  65. },
  66. textColor: '#d1d4dc',
  67. },
  68. grid: {
  69. vertLines: {
  70. visible: false,
  71. },
  72. horzLines: {
  73. color: 'rgba(42, 46, 57, 0.5)',
  74. },
  75. },
  76. rightPriceScale: {
  77. borderVisible: false,
  78. },
  79. timeScale: {
  80. borderVisible: false,
  81. },
  82. crosshair: {
  83. horzLine: {
  84. visible: false,
  85. },
  86. },
  87. });
  88. const currentLocale = window.navigator.languages[0];
  89. const myPriceFormatter = Intl.NumberFormat(currentLocale, {
  90. style: "currency",
  91. currency: "USD", // Currency for data points
  92. }).format;
  93. chart.applyOptions({
  94. localization: {
  95. priceFormatter: myPriceFormatter,
  96. },
  97. });
  98. document.body.appendChild(chartElement);
  99. 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)

huangapple
  • 本文由 发表于 2023年8月5日 11:12:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76840016.html
匿名

发表评论

匿名网友

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

确定