Dates change when passing from back end function to front end function - javascript

Let me start off by apologizing for the length of this post but I want to be as verbose as possible as this issue is very interesting and weird.
I am rendering a date picker with room availability for resorts that my company manages. This is accomplished with two functions (one back end function and one front end function).
The back end function makes a request to an external API, formats the response into an array of date objects and returns the array.
The front end function calls the back end function and then pushes the response onto an object that renders the availability.
The array of date objects is not changed or mutated in any way after it is formatted by the back end function. Yet somehow the dates that are rendered on the front end are always one day before the date that is returned from the back end function.
I know that sounds confusing so let me clarify.
Here is the array of date objects that is returned from the back end function:
correct dates
Here is what is rendered to the date picker:
Incorrect dates
At first I was almost convinced that the date picker was just getting the dates wrong so I did a bit more digging and found out that the dates that are stored in the array are somehow changing as they are being passed back to the front end function.
Here is the code for the front end function that is applicable:
getAvailAsync(startDate, endDate, attributeId, resortId, room, resort, duration).then(response => {
console.log("returned to front end", response.res.availability)
response.res.error ? "" : repeaterData.push(response.res)
$w("#resortsRepeater").data = repeaterData
if(repeaterData.length > 12) {
$w("#loadMore").show()
}
if(repeaterData.length > 0) {
$w("#loadingStrip").collapse()
}
})
Here is what is logged to the console from the front end:
[
{
"startDate": "Fri Jul 15 2022 17:00:00 GMT-0700 (Pacific Daylight Time)",
"endDate": "Fri Jul 15 2022 17:00:00 GMT-0700 (Pacific Daylight Time)"
},
{
"startDate": "Sat Jul 16 2022 17:00:00 GMT-0700 (Pacific Daylight Time)",
"endDate": "Sat Jul 16 2022 17:00:00 GMT-0700 (Pacific Daylight Time)"
},
{
"startDate": "Sun Jul 17 2022 17:00:00 GMT-0700 (Pacific Daylight Time)",
"endDate": "Sun Jul 17 2022 17:00:00 GMT-0700 (Pacific Daylight Time)"
},
{
"startDate": "Mon Jul 18 2022 17:00:00 GMT-0700 (Pacific Daylight Time)",
"endDate": "Mon Jul 18 2022 17:00:00 GMT-0700 (Pacific Daylight Time)"
},
{
"startDate": "Tue Jul 19 2022 17:00:00 GMT-0700 (Pacific Daylight Time)",
"endDate": "Tue Jul 19 2022 17:00:00 GMT-0700 (Pacific Daylight Time)"
},
{
"startDate": "Tue Jul 26 2022 17:00:00 GMT-0700 (Pacific Daylight Time)",
"endDate": "Tue Jul 26 2022 17:00:00 GMT-0700 (Pacific Daylight Time)"
}
]
As you can see the first date is July 15th and the last date is July 26th.
Now here is the applicable code from the back end getAvailAsync function:
if(validAvail == undefined) {
resolve({ res: {error: "No availability found"}})
} else {
console.log("Valid avail before passing to the front end", validAvail)
validAvail.length > 0
?
resolve({
res: {
...resortInfo,
...roomInfo,
availability: validAvail
}
})
: resolve({
res: {error: "No availability found"}
})
}
Here is what is logged to the console from the back end function:
[
{
"startDate": "2022-07-16T00:00:00.000Z",
"endDate": "2022-07-16T00:00:00.000Z"
},
{
"startDate": "2022-07-17T00:00:00.000Z",
"endDate": "2022-07-17T00:00:00.000Z"
},
{
"startDate": "2022-07-18T00:00:00.000Z",
"endDate": "2022-07-18T00:00:00.000Z"
},
{
"startDate": "2022-07-19T00:00:00.000Z",
"endDate": "2022-07-19T00:00:00.000Z"
},
{
"startDate": "2022-07-20T00:00:00.000Z",
"endDate": "2022-07-20T00:00:00.000Z"
},
{
"startDate": "2022-07-27T00:00:00.000Z",
"endDate": "2022-07-27T00:00:00.000Z"
}
]
As you can see the first date is July 16th and the last date is July 27th.
What's more is every single date has been decremented by 1 somehow.
I am completely clueless as to why this is happening. The only thing that I can think of is that the back end function has a date object for the start date and end date after being returned from the API (see the first image where it says {"startDate": {$date: "2022-07-02...}, ...}
Could that somehow be messing up the date? And if so how do I resolve this?

As pilchard mentioned this issue was related to the changing of time zones when the date object was passed to the front end and rendered to the screen. I just had to set the hour manually to noon using date.setHours(). This way the date was not changed when the timezone changed.

Related

Need exactly _d value of moment-react

I need the exact value of _d in moment-react.
_d: Wed Aug 10 2022 16:34:56 GMT+0530 (India Standard Time) {}
_isAMomentObject: true
_isUTC: false
_isValid: true
When doing moment.toString(), I am getting "Wed Aug 10 2022 16:34:56 GMT+0530" but I need "Wed Aug 10 2022 16:34:56 GMT+0530 (India Standard Time)"

Subtracting months from current date is returning unexpected results. Same Month (March) is being returned twice

I have created a method that returns the past months according to the current date and how many months from the past you need, seems like the javascript date object is
behaving wrongly.
I guess the problem has only popped up today as it's the 29th of the current month and subtracting 1 month from 29 March which is supposed to be 29 February (doesn't exist) lead javascript to fallback to +1 day...
Can someone please suggest a great fix for this.
Thanks 🙌
export type Config = {
n: number;
i18n: i18n;
};
export default function NMonthsAgo(config: Config): MonthsAgo[] {
const date = new Date();
const { i18n } = config;
let { n } = config;
n = Math.max(n, 0);
// add one month in future to include the current one.
date.setMonth(date.getMonth() + 1);
return Array.from({ length: n || 1 })
.map(() => {
date.setMonth(date.getMonth() - 1);
console.log(date.toDateString()); ===> console print.
return {
monthName: formatDate(i18n, date, { month: 'long' }),
monthNameShort: formatDate(i18n, date, { month: 'short' }),
year: formatDate(i18n, date, { year: 'numeric' }),
};
})
.reverse();
}
Output:
NMonthsAgo.js:36 Wed Dec 29 2021
NMonthsAgo.js:36 Mon Nov 29 2021
NMonthsAgo.js:36 Fri Oct 29 2021
NMonthsAgo.js:36 Wed Sep 29 2021
NMonthsAgo.js:36 Sun Aug 29 2021
NMonthsAgo.js:36 Thu Jul 29 2021
NMonthsAgo.js:36 Tue Jun 29 2021
NMonthsAgo.js:36 Sat May 29 2021
NMonthsAgo.js:36 Thu Apr 29 2021
NMonthsAgo.js:36 Mon Mar 29 2021 <=== Mars is returned twice...
NMonthsAgo.js:36 Mon Mar 01 2021 <=== Mars is returned twice...
NMonthsAgo.js:36 Mon Feb 01 2021
NMonthsAgo.js:36 Fri Jan 01 2021
NMonthsAgo.js:36 Wed Dec 29 2021

javascript string date from array and group by day and return new array per day

I got a array of data the data is dates they are sorted per day.
Wat i want to get is the data grouped by date(day) and all the data of every day needs to be in new and separated array. my data can be short 1 date string in 1 day or very long month's or year
My data:
accountDateArray = [
Mon Jun 08 2020 19:47:16 GMT+0200 (Midden-Europese zomertijd),
Mon Jun 08 2020 19:47:26 GMT+0200 (Midden-Europese zomertijd),
Mon Jun 08 2020 19:47:34 GMT+0200 (Midden-Europese zomertijd),
Tue Jun 09 2020 15:40:31 GMT+0200 (Midden-Europese zomertijd),
Tue Jun 09 2020 15:42:28 GMT+0200 (Midden-Europese zomertijd),
Wed Jun 10 2020 00:06:50 GMT+0200 (Midden-Europese zomertijd),
Wed Jun 10 2020 00:06:50 GMT+0200 (Midden-Europese zomertijd),
Wed Jun 10 2020 08:10:51 GMT+0200 (Midden-Europese zomertijd),
Fri Jun 12 2020 10:59:21 GMT+0200 (Midden-Europese zomertijd),
...
]
What i want is:
[
[
Mon Jun 08 2020 19:47:16 GMT+0200 (Midden-Europese zomertijd),
Mon Jun 08 2020 19:47:26 GMT+0200 (Midden-Europese zomertijd),
Mon Jun 08 2020 19:47:34 GMT+0200 (Midden-Europese zomertijd),
],
[
Tue Jun 09 2020 15:40:31 GMT+0200 (Midden-Europese zomertijd),
Tue Jun 09 2020 15:42:28 GMT+0200 (Midden-Europese zomertijd),
],
...
]
My code
let NewDateArray = [];
for (let i in accountDateArray) {
NewDateArray.push(accountDateArray[i].toString().substring(0, 10));
}
let unique = [...new Set(NewDateArray)];
for (let i in accountDateArray) {
for (let n in unique) {
if (
unique[n] === accountDateArray[i].toString().substring(0, 10)
) {
console.log(accountDateArray[i]);
}
}
}
You can make use of reduce function, I hope this will lead you to the right direction.
var accountDateArray = ['Mon Jun 08 2020 19:47:16 GMT+0200 (Midden-Europese zomertijd)','Mon Jun 08 2020 19:47:26 GMT+0200 (Midden-Europese zomertijd)','Mon Jun 08 2020 19:47:34 GMT+0200 (Midden-Europese zomertijd)','Tue Jun 09 2020 15:40:31 GMT+0200 (Midden-Europese zomertijd)','Tue Jun 09 2020 15:42:28 GMT+0200 (Midden-Europese zomertijd)','Wed Jun 10 2020 00:06:50 GMT+0200 (Midden-Europese zomertijd)','Wed Jun 10 2020 00:06:50 GMT+0200 (Midden-Europese zomertijd)','Wed Jun 10 2020 08:10:51 GMT+0200 (Midden-Europese zomertijd)','Fri Jun 12 2020 10:59:21 GMT+0200 (Midden-Europese zomertijd)',];
var result = Object.values(accountDateArray.reduce((acc, date)=>{
const key = new Date(date).getDate();
acc[key] = [...(acc[key] || []), date];
return acc;
},{}));
console.log(result);

How to group json object dates by month?

I have a JSON object like so:
{
"Sat Jul 28 2018 03:36:36 GMT-0700 (Pacific Daylight Time)":[
{ ... },
{ ... }
],
"Fri Aug 03 2018 19:07:14 GMT-0700 (Pacific Daylight Time)":[
{ ... }
],
"Sat Aug 18 2018 17:25:50 GMT-0700 (Pacific Daylight Time)":[
{ ... }
]
}
How can I return this into a grouped object by month?
Try this (with lodash):
var input = {
"Sat Jul 28 2018 03:36:36 GMT-0700 (Pacific Daylight Time)": [
"test", "tester"
],
"Fri Aug 03 2018 19:07:14 GMT-0700 (Pacific Daylight Time)": [
"tester1"
],
"Sat Aug 18 2018 17:25:50 GMT-0700 (Pacific Daylight Time)": [
"tester2"
]
}
var groupedKeys = _.groupBy(Object.keys(input), function(key) {
return key.substring(4, 7)
});
var groupedEntries = _.map(groupedKeys, (values, key) => {
values = _.map(values, (value) => {
return input[value]
});
return {
key: key,
values: _.flattenDeep(values)
};
});
var result = _.reduce(groupedEntries, (result, obj) => {
result[obj.key] = obj.values;
return result;
}, {})
console.log(result);
Output:
{
"Jul": [
"test",
"tester"
],
"Aug": [
"tester1",
"tester2"
]
}
Loop through the object then extract month and create new object:
let jsonObj = {
"Sat Jul 28 2018 03:36:36 GMT-0700 (Pacific Daylight Time)":[{},{}],
"Fri Aug 03 2018 19:07:14 GMT-0700 (Pacific Daylight Time)":[{}],
"Sat Aug 18 2018 17:25:50 GMT-0700 (Pacific Daylight Time)":[{}]
};
let grouped = Object.keys(jsonObj).reduce((prev,key,i,all)=>{
let monthArr = {};
if(typeof prev === 'string'){
monthArr[prev.substr(4,3)] = jsonObj[prev];
prev = {};
}
monthArr[key.substr(4,3)] = jsonObj[key];
return {...prev,...monthArr};
});

Javascript sorting with two properties

I'm struggling with sorting two levels. The logic is as follows. If any of the objects have a status, return the most recent object with a status. If none of the objects have a status, return the most recent object without a status.
var apps = [
{ status: 'PASS',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)
},
{ status: 'FAIL',
date_created: Thu Sep 02 2015 17:24:45 GMT-0700 (PDT),
},
{ status: '',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT),
}
]
var desired_result = [{ status: 'PASS',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)
}]
var apps_2 = [
{ status: '',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)
},
{ status: '',
date_created: Thu Sep 02 2015 17:24:45 GMT-0700 (PDT),
},
{ status: '',
date_created: Thu Sep 01 2015 17:24:45 GMT-0700 (PDT),
}
]
var desired_resul2 = [{ status: '',
date_created: Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)
}]
I've tried
var sorted = _.sort_by(apps, function (x) { x.date_updated });
I've also looked a few other SO questions but can't keep the objects in place after the first sort.
If I understand your question correctly, here is what you are looking for. http://jsfiddle.net/whxu5sea/3/
You need to filter the elements to ensure they have a status of ANY kind. Then sort them by date, earliest first. Then get that first value. In my example I assumed the dates where strings, but still should work.
var apps = [
{ status: 'PASS',
date_created: 'Thu Sep 03 2015 17:24:45 GMT-0700 (PDT)'
},
{ status: 'FAIL',
date_created: 'Thu Sep 02 2015 17:24:45 GMT-0700 (PDT)',
},
{ status: '',
date_created: 'Thu Sep 01 2015 17:24:45 GMT-0700 (PDT)',
}
];
var x;
var arr = _.filter(apps, function(data) {
return !!data.status.length;
});
x = _.chain( arr.length ? arr : apps )
.sortBy(function(data) {
return new Date(data.date_created).getTime();
}).last().value();
console.log( x );
To check if it works when no status is provided: http://jsfiddle.net/whxu5sea/4/
I hope this helps. LMK if any further clarification is needed.
EDIT: Updated to get NEWEST element (last).
Here is a simple solution that iterates just once through apps, without a filtering step. See here for a jsfiddle.
The concept is that, if status is falsy, its date is converted into a negative number that retains the correct sort order among all falsy elements, but makes all falsy elements have a lower sort order than all non-falsy ones.
We convert the falsy element dates by subtracting 8640000000000001, which is (the maximimum millis in a Date, plus one).
var x = _.chain(apps).sortBy(function(x) {
var date = new Date(x.date_created).getTime();
return x.status ? date : date - 8640000000000001;
}).last().value();
console.log( x );

Categories