gpt4 book ai didi

javascript - 迭代日期数组的函数会产生意想不到的结果

转载 作者:行者123 更新时间:2023-11-30 16:32:28 25 4
gpt4 key购买 nike

我有一个从我的 iOS 应用调用的 CloudCode 函数。该函数应该创建一个“签到”记录并返回一个字符串来表示最近 30 天的签到和错过的天数。

奇怪的是,有时我会得到预期的结果,有时却得不到。这让我觉得我使用时区可能存在一些问题 - 因为这可能会导致一组不同的“过去的日子”,具体取决于我运行此功能的时间以及我在一天中的什么时间 checkin 过去。但我很困惑,在这里需要一些帮助。

让我感到困惑的是,我没有看到我的所有 console.log() 结果都出现在解析日志中。这正常吗??例如,在 for 循环中,我可以取消注释 console.log 条目并调用该函数,但我不会看到列出的所有过去的日子 - 但它们包含在最终数组和文本字符串中。

这是我的完整功能。感谢您提供任何帮助和建议。

/* Function for recording a daily check in
*
* Calculates the number of days missed and updates the string used to display the check-in pattern.
* If no days missed then we increment the current count
*
* Input:
* "promiseId" : objectID,
* "timeZoneDifference" : String +07:00
*
* Output:
* JSON String eg. {"count":6,"string":"000000000000001111101010111111"}
*
*/
Parse.Cloud.define("dailyCheckIn", function(request, response) {
var promiseId = request.params.promiseId;
var timeZoneDifference = request.params.timeZoneDifference;
var currentUser = Parse.User.current();

if (currentUser === undefined) {
response.error("You must be logged in.");
}

if (timeZoneDifference === undefined || timeZoneDifference === "") {
//console.log("timeZoneDifference missing. Set to -07:00");
timeZoneDifference = '' + '-07:00'; // PacificTime as string
}

var moment = require('cloud/libs/moment.js');

// Query for the Promise
var Promise = Parse.Object.extend("Promise");
var queryforPromise = new Parse.Query(Promise);

queryforPromise.get(promiseId, {
success: function(promis) {

// Initialize
var dinarowString = "";
var dinarowCount = 0;

// Last Check In date from database (UTC)
var lastCheckInUTC = promis.get("lastCheckIn");
if (lastCheckInUTC === undefined) {
lastCheckInUTC = new Date(2015, 1, 1);
}

// Use moment() to convert lastCheckInUTC to local timezone
var lastCheckInLocalized = moment(lastCheckInUTC.toString()).utcOffset(timeZoneDifference);
//console.log('lastCheckIn: ' + lastCheckInUTC.toString());
//console.log('lastCheckInLocalized: ' + lastCheckInLocalized.format());

// Use moment() to get "now" in UTC timezone
var today = moment().utc(); // new Date();
//console.log('today: ' + today.format());

// Use moment() to get "now" in local timezone
var todayLocalized = today.utcOffset(timeZoneDifference);
//console.log('todayLocalized: ' + todayLocalized.format());

// 30 days in the past
var thirtydaysago = moment().utc().subtract(30, 'days');
//console.log("thirtydaysago = " + thirtydaysago.format());

// 30 days in the past in local timezone
var thirtydaysagoLocalized = thirtydaysago.utcOffset(timeZoneDifference);
//console.log('thirtydaysagoLocalized: ' + thirtydaysagoLocalized.format());

// Calculate the number of days since last time user checked in
var dayssincelastcheckin = todayLocalized.diff(lastCheckInLocalized, 'days');
//console.log("Last check-in was " + dayssincelastcheckin + " days ago");

// Function takes an array of Parse.Objects of type Checkin
// itterate over the array to get a an array of days in the past as numnber
// generate a string of 1 and 0 for the past 30 days where 1 is a day user checked in
function dinarowStringFromCheckins(checkins) {
var days_array = [];
var dinarowstring = "";

// Create an array entry for every day that we checked in (daysago)
    for (var i = 0; i < checkins.length; i++) {
var checkinDaylocalized = moment(checkins[i].get("checkInDate")).utcOffset(timeZoneDifference);
var daysago = todayLocalized.diff(checkinDaylocalized, 'days');
// console.log("daysago = " + daysago);
days_array.push(daysago);
}
console.log("days_array = " + days_array);

// Build the string with 30 day of hits "1" and misses "0" with today on the right
    for (var c = 29; c >= 0; c--) {
if (days_array.indexOf(c) != -1) {
//console.log("days ago (c) = " + c + "-> match found");
dinarowstring += "1";
} else {
dinarowstring += "0";
}
}
return dinarowstring;
}

// Define ACL for new Checkin object
var checkinACL = new Parse.ACL();
checkinACL.setPublicReadAccess(false);
checkinACL.setReadAccess(currentUser, true);
checkinACL.setWriteAccess(currentUser, true);

// Create a new entry in the Checkin table
var Checkin = Parse.Object.extend("Checkin");
var checkin = new Checkin();
checkin.set("User", currentUser);
checkin.set("refPromise", promis);
checkin.set("checkInDate", today.toDate());
checkin.setACL(checkinACL);
checkin.save().then(function() {
// Query Checkins
var Checkin = Parse.Object.extend("Checkin");
var queryforCheckin = new Parse.Query(Checkin);
queryforCheckin.equalTo("refPromise", promis);
queryforCheckin.greaterThanOrEqualTo("checkInDate", thirtydaysago.toDate());
queryforCheckin.descending("checkInDate");
queryforCheckin.find().then(function(results) {
var dinarowString = "000000000000000000000000000000";
var dinarowCount = 0;
if (results.length > 0) {
dinarowString = dinarowStringFromCheckins(results);
dinarowIndex = dinarowString.lastIndexOf("0");
if (dinarowIndex === -1) { // Checked in every day in the month!
// TODO
// If the user has checked in every day this month then we need to calculate the
// correct streak count in a different way
dinarowString = "111111111111111111111111111111";
dinarowCount = 999;
} else {
dinarowCount = 29 - dinarowIndex;
}
}
// Update the promise with new value and save
promis.set("dinarowString", dinarowString);
promis.set("dinarowCount", dinarowCount);
promis.set("lastCheckIn", today.toDate());
promis.save().then(function() {
response.success(JSON.stringify({
count: dinarowCount,
string: dinarowString
}));
});
}, function(reason) {
console.log("Checkin query unsuccessful:" + reason.code + " " + reason.message);
response.error("Something went wrong");
});

}); // save.then
},
error: function(object, error) {
console.error("dailyCheckIn failed: " + error);
response.error("Unable to check-in. Try again later.");
}
});
});

最佳答案

你的问题太多了,无法充分回答,但我会很好,至少指出一些你应该研究的错误:

  1. 您根据固定偏移量进行输入,但随后您进行的运算会减去 30 天。您完全有可能跨越夏令时边界,在这种情况下,偏移量将发生变化。

    请参阅 timezone tag wiki 中的“时区!= 偏移量” .此刻,您可以使用时区名称,例如 "America/Los_Angeles"moment-timezone附加组件。

    根据您的示例,我什至不确定时区对您的用例是否重要。

  2. 您不应将 Date 转换为字符串只是为了再次解析它。假定 Date 对象已正确创建,Moment 可以接受 Date 对象。

    moment(lastCheckInUTC.toString()).utcOffset(timeZoneDifference)

    成为

    moment(lastCheckInUTC).utcOffset(timeZoneDifference)

    由于 Date.toString() 返回特定于语言环境、特定于实现的格式,您还会在调试控制台中看到一条警告。

至于其余部分,我们无法运行您的程序并重现结果,因此我们无能为力。您需要先调试自己的程序,然后尝试在 Minimal, Complete, and Verifiable example 中重现您的错误。 .很有可能,您会一路解决自己的问题。如果没有,那么您将有更好的状态与我们分享。

关于javascript - 迭代日期数组的函数会产生意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33136455/

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