gpt4 book ai didi

javascript - 选择一个日期,然后将格式从 UNIX 转换为 UTC(yyyymmdd)

转载 作者:行者123 更新时间:2023-11-28 00:21:10 25 4
gpt4 key购买 nike

目标:将 block 末尾的数组中的日期设置为:yyyymmdd(包括零)。 (示例数据构建:numDaysAPITimes = [20150403])。我得到的是没有正确获取月份,并且 numDaysAPITimes 数组由于某种原因仅存储年份。

    var totalPrecipSinceDate;
var numDaysAPITimes = [];
var userDataDatePick = document.getElementById('dateRngPick').value;

if (userDataDatePick >=1)
{
for (var i = 0; i <= (userDataDatePick-1); i++) //place user userData-1 where i <= input
{
var myDate = new Date(); //http://stackoverflow.com/questions/7693170/javascript-convert-from-epoch-string-to-date-object
var epoch = myDate.getTime();
var unixEpoch = Math.round(epoch/1000)
var backDateEpochTime = Math.round(unixEpoch - (86400 * i)); //Get each day (UNIX seconds)
var d = new Date(backDateEpochTime); //Convert to UTC
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();

numDaysAPITimes[i] = (curr_year + curr_month + curr_date);
}
}
else
{
alert("You have not entered a valid number for the date.");

numDaysAPITimes.length = 0;
}

最佳答案

一些事情:

  1. 您的日期信息以数字形式相加,这就是为什么这一年似乎只是过去了。处理这个问题的一种方法是使用 toString() 方法。

  2. 您可能需要在日期和月份中添加前导零,这可以通过在前面添加 0 然后执行切片 -2 来实现。

看起来像 This JSFiddle, or :

    var totalPrecipSinceDate;
var numDaysAPITimes = [];
var userDataDatePick = 2;//document.getElementById('dateRngPick').value;

if (userDataDatePick >=1)
{
for (var i = 0; i <= (userDataDatePick-1); i++) //place user userData-1 where i <= input
{
var myDate = new Date(); //http://stackoverflow.com/questions/7693170/javascript-convert-from-epoch-string-to-date-object
var epoch = myDate.getTime();
var unixEpoch = Math.round(epoch/1000)
var backDateEpochTime = Math.round(unixEpoch - (86400 * i)); //Get each day (UNIX seconds)
var d = new Date((1000*backDateEpochTime)); //Convert to UTC
var curr_date = ("0" + d.getDate()).slice(-2)
var curr_month = ("0"+ (d.getMonth() + 1)).slice(-2); //Months are zero based
var curr_year = d.getFullYear();
console.log(d.getMonth());
numDaysAPITimes[i] = (curr_year.toString() + curr_month.toString() + curr_date.toString());
}
}
else
{
alert("You have not entered a valid number for the date.");

numDaysAPITimes.length = 0;
}
console.log(numDaysAPITimes)

关于javascript - 选择一个日期,然后将格式从 UNIX 转换为 UTC(yyyymmdd),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30016187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com