So, I am working on a time registration management tool. I have a date picker component where I choose the date I want to see the registrations from. It gives me the Unix timestamp of that day and I store that value, fx. 1606856503.
Now, I am retrieving all registrations from the API, which is an array of objects where each object is a registration. Each registration has a date property, which is basically a Unix timestamp from the date it was created.
[{
"id": "1",
"userId": "userId 1",
"customerId": "customerId 1",
"case": "case 1",
"description": "description 1",
"hours": 72,
"date": 1606826246,
"customer": "customer 1",
"project": "project 1"
}]
Now, that I have a date picker Unix timestamp, I would like to filter the registrations in order to filter and display only registrations which were made on the day of the Unix timestamp from the picker, but can't figure out how would I compare them and filter based on the day.
Here's a quick snippet illustrating using either Date.prototype.toISOString() or Date.prototype.toDateString() to filter against a specified timestamp.
Since your timestamps are stored in seconds and javascript dates use milliseconds, you need to multiply by 1000 when creating your dates
const filterTimestamp = 1606859476; // Tuesday, December 1, 2020 9:51:16 PM
const filterDate = new Date(filterTimestamp*1000);
You can then filter by comparing the first 10 characters of the date strings returned by toISOString() which will always keep the timezone as zero UTC offset
const filterDateString = new Date(filterTimestamp*1000).toISOString().slice(0, 10);
// "2020-12-01" sliced from "2020-12-01T21:51:16.000Z"
const regsOnDate = regs.filter(o => (
new Date(o.date*1000).toISOString().slice(0, 10) === filterDateString));
or by the date strings returned by toDateString() which will use the local timezone
const filterDateString = new Date(filterTimestamp*1000).toDateString();
const regsOnDate = regs.filter(o => (
new Date(o.date*1000).toDateString() === filterDateString));
// eg: compares "Mon Nov 02 2020" to "Tue Dec 01 2020"
Using toISOString()
const regs = [
{
"id": "1",
"date": 1606826246, // Tuesday, December 1, 2020 12:37:26 PM
"customer": "customer 1",
},
{
"id": "2",
"date": 1604353553, // Monday, November 2, 2020 9:45:53 PM
"customer": "customer 2",
},
{
"id": "3",
"date": 1606860022, // Tuesday, December 1, 2020 10:00:22 PM
"customer": "customer 3",
}
]
const filterTimestamp = 1606859476; // Tuesday, December 1, 2020 9:51:16 PM
const filterDateString = new Date(filterTimestamp*1000).toISOString().slice(0, 10);
// "2020-12-01" sliced from "2020-12-01T21:51:16.000Z"
const regsOnDate = regs.filter(o => (
new Date(o.date*1000).toISOString().slice(0, 10) === filterDateString));
console.log( regsOnDate );
Using toDateString()
const regs = [
{
"id": "1",
"date": 1606826246, // Tuesday, December 1, 2020 12:37:26 PM
"customer": "customer 1",
},
{
"id": "2",
"date": 1604353553, // Monday, November 2, 2020 9:45:53 PM
"customer": "customer 2",
},
{
"id": "3",
"date": 1606860022, // Tuesday, December 1, 2020 10:00:22 PM
"customer": "customer 3",
}
]
const filterTimestamp = 1606859476; // Tuesday, December 1, 2020 9:51:16 PM
const filterDateString = new Date(filterTimestamp*1000).toDateString();
const regsOnDate = regs.filter(o => (
new Date(o.date*1000).toDateString() === filterDateString));
console.log( regsOnDate );
UNIX timestamps are seconds since 1 Jan 1970 UTC, ECMAScript time values are milliseconds since the same epoch, see Convert a Unix timestamp to time in JavaScript.
If you just want to compare values for the same date UTC, you can just compare whole days since the epoch. That means a simple arithmetic operation on the value rather than using Date objects. e.g.
let data = [{"id": "1","date": 1606826246}, // 1 Dec 2020 UTC
{"id": "2","date": 1606867200}, // 2 Dec 2020 UTC
{"id": "3","date": 1606953600} // 3 Dec 2020 UTC
];
// Start with date sometime on 2 Dec 2020 UTC
let d = new Date(Date.UTC(2020,11,2,8,32,21)); // 2 Dec 2020 08:32:21 Z
console.log('Test date: ' + d.toISOString());
// Get whole days since epoch
let daysSinceEpoch = d.getTime() / 8.64e7 | 0;
console.log('daysSinceEpoch: ' + daysSinceEpoch);
// Find matching records in data
let result = data.filter(obj => (obj.date / 8.64e4 | 0) == daysSinceEpoch);
console.log('Matching records: ' + JSON.stringify(result));
// Matching date values
console.log('Matching dates:');
result.forEach(obj => console.log('id: ' + obj.id + ' on ' + new Date(obj.date * 1000).toISOString().substr(0,10)));
You can do the same thing with local dates, you just need to be a bit more careful of getting the days, see How do I get the number of days between two dates in JavaScript?
Related
How to convert the 1 object with multiple item inside to an array of object? please see the picture below to understand what i meant, thanks
var author = (`SELECT author, title, remarks, status, date FROM Transaction`, 1000, data=>{
let obj = {[author: [], book: [], condition: [], status: [], date: []]}
for(let x = 0; x < data.length; x++){
obj.author.push(data[x][0]);
obj.book.push(data[x][1]);
obj.condition.push(data[x][2]);
obj.status.push(data[x][3]);
obj.date.push(data[x][4]);
}
console.log("obj: ", obj)
return resolve(obj);
})
The Current result of console.log("obj: ", obj)
{
"authors": "testuser,testname",
"books": "440936785,440936694",
"conditions": "Very Good,New,",
"status": "Not Available,Available",
"datepublished": "Mon Mar 28 2022 18:42:24 GMT+0800 (Philippine Standard Time),Mon Mar 28 2022 18:42:39 GMT+0800 (Philippine Standard Time)"
}
What I want result:
{
"authors": "testname",
"books": "440936694",
"conditions": "New",
"status": "Available",
"datepublished": "Mon Mar 28 2022 18:42:24 GMT+0800 (Philippine Standard Time)"
},
{
"authors": "testname",
"books": "440936694",
"conditions": "New,",
"status": "Available",
"datepublished": "Mon Mar 28 2022 18:42:39 GMT+0800 (Philippine Standard Time)"
}
You have a list of rows and want to create a list of objects. That means you have to convert every row to an object. Such a transformation is typically done with Array#map, which applies a function to every element in an array a produces a new array from the return value of that function:
const objects = data.map(row => ({
author: row[0],
book: row[1],
condition: row[2],
status: row[3],
date: row[4],
}));
The library you are using to query the database might also be able to already create an object per row (using the column names) so you don't have to do the mapping yourself.
I'm referring to this answer again.
var firstEvents = events.reduce(function(ar, e) {
var id = e.getId();
if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) {
ar.push({eventTitle: e.getTitle(), eventId: id, startDate: e.getAllDayStartDate(), endDate: e.getAllDayEndDate()});
}
return ar;
}, []);
What do I have to change to get an array with the event titles (Strings) as keys and the start dates (Date objects) as values so I can retrieve a certain start date (Date object) via firstEvents['some event title']?
EDIT:
Current Ouput:
firstEvents = [{eventTitle=Event title 1, eventId=xyz1#google.com, startDate=Sun Mar 18 00:00:00 GMT+01:00 2018, endDate=Mon Mar 19 00:00:00 GMT+01:00 2018},
{eventTitle=Event title 2, eventId=xyz2#google.com, startDate=Tue Mar 19 00:00:00 GMT+01:00 2019, endDate=Wed Mar 20 00:00:00 GMT+01:00 2019},
{eventTitle=Event title 3, eventId=xyz3#google.com, startDate=Fri Mar 20 00:00:00 GMT+01:00 2020, endDate=Sat Mar 21 00:00:00 GMT+01:00 2020}]
Needed Output (Pseudo):
firstEvents = ['Event title 1' => Sun Mar 18 00:00:00 GMT+01:00 2018,
'Event title 2' => Tue Mar 19 00:00:00 GMT+01:00 2019,
'Event title 3' => Fri Mar 20 00:00:00 GMT+01:00 2020]
Do not use push, but set to object with key.
ar = {}; // You may need to change source parameter too
// you cannot change input Array [] to Object {} type inside function
// you can get Array and return Object, but source variable will not change
ar[e.getTitle()] = e.getAllDayStartDate();
Or using some demo data:
var ar = [
{
eventTitle: 'one',
eventId: '#1',
startDate: new Date(),
endDate: new Date()
},
{
eventTitle: 'two',
eventId: 'secondId',
startDate: new Date(),
endDate: new Date()
}];
var retVal = {};
for (var i of ar) {
retVal[i.eventId] = i;
}
console.log(JSON.stringify(retVal, null, 2));
console.log(retVal['#1']);
console.log(retVal.secondId);
I have one JSON data, which contains date like jan 23,2018.
How can I compare JSON data date with the current date?
[
{
"id": "user_1",
"date": "jan 23, 2019"
},
{
"id": "user_2",
"date": "mar 3, 2017"
},
{
"id": "user_3",
"date": "feb 23, 2019"
}
]
How can I get data which has the date is more than current date using jmespath?
const array = [
{
"id": "user_1",
"date": "jan 23, 2019"
},
{
"id": "user_2",
"date": "mar 3, 2017"
},
{
"id": "user_3",
"date": "feb 23, 2019"
}
];
const newArray = array.map((value) => {
value.date = new Date(value.date).getTime();
return value;
});
console.log(newArray);
console.log('current time in milliseconds ', new Date().getTime());
/* array.forEach((value) => {
const date = new Date(value.date);
console.log(date);
}); */
// console.log('current date', new Date());
Loop array and pass date string to new Date() to get date object and then you can compare it to current date.
EDIT: Now you can directly use milisecond to compare the dates.
You can use JMESPath Custom functions to achieve that. You'll need to convert your date to epoch in order to compare the dates because JMESPath doesn't understand date object.
You can refer an example here under Custom function section: https://pypi.org/project/jmespath/
I created my own custom function to check whether a past date has surpassed current time by atleast certain amount of seconds. Here's my code:
from jmespath import functions
import time
class CustomFunctions(functions.Functions):
# the function name should always have a prefix of _func_ for it to be considered
#functions.signature({'types': ['string']}, {'types': ['number']})
def _func_hasTimeThresholdCrossed(self, jobdate, difference):
jobdate = time.strptime(jobdate,'%Y-%m-%dT%H:%M:%S.%fZ')
return time.time() - time.mktime(jobdate) > difference
options = jmespath.Options(custom_functions=CustomFunctions())
jmespath.search("hasTimeThresholdCrossed(createdAt,`1000000`)",{"createdAt":"2019-03-22T10:49:17.342Z"},options=options)
I have JavaScript function called updateLatestDate that receive as parameter array of objects.
One of the properties of the object in array is the MeasureDate property of date type.
The function updateLatestDate returns the latest date existing in array.
Here is the function:
function updateLatestDate(sensorsData) {
return new Date(Math.max.apply(null, sensorsData.map(function (e) {
return new Date(e.MeasureDate);
})));
}
And here is the example of parameter that function receive:
[{
"Address": 54,
"AlertType": 1,
"Area": "North",
"MeasureDate": "2009-11-27T18:10:00",
"MeasureValue": -1
},
{
"Address": 26,
"AlertType": 1,
"Area": "West",
"MeasureDate": "2010-15-27T15:15:00",
"MeasureValue": -1
},
{
"Address": 25,
"AlertType": 1,
"Area": "North",
"MeasureDate": "2012-10-27T18:10:00",
"MeasureValue": -1
}]
The function updateLatestDate will return MeasureDate value of last object in the array.
And it will look like that:
var latestDate = Sat Oct 27 2012 21:10:00 GMT+0300 (Jerusalem Daylight Time)
As you can see the time of the returned result is different from the time of the input object.The time changed according to GMT.
But I don't want the time to be changed according to GMT.
The desired result is:
var latestDate = Sat Oct 27 2012 18:10:00
Any idea how can I ignore time zone when date returned from updateLatestDate function?
As Frz Khan pointed, you can use the .toISOString() function when returning the date from your function, but if you're seeking the UTC format, use the .toUTCString(), it would output something like Mon, 18 Apr 2016 18:09:32 GMT
function updateLatestDate(sensorsData) {
return new Date(Math.max.apply(null, sensorsData.map(function (e) {
return new Date(e.MeasureDate).toUTCString();
})));
}
The Date.toISOString() function is what you need
try this:
var d = new Date("2012-10-27T18:10:00");
d.toISOString();
result:
"2012-10-27T18:10:00.000Z"
If you use moment it will be
moment('Sat Oct 27 2012 21:10:00 GMT+0300', 'ddd MMM DD DDDD HH:mm:SS [GMT]ZZ').format('ddd MMM DD YYYY HH:mm:SS')
Let's say you have the following object as a string:
var timecard = {
"name": "Joe",
"time": "Sun Apr 26 2015 13:58:54 GMT-0400 (EDT)"
}
// as string
var stringed = 'var timecard = { "name": "Joe", "time": "Sun Apr 26 2015 13:58:54 GMT-0400 (EDT)" }'
and you run JSON.parse(stringed) to parse it into the object. How would you go about having it convert the date into an actual Date object as opposed to a string?
Thanks!
The JSON data format doesn't have a date type, so you have to write the code to transform it into a Date object yourself.
You can pass a reviver function as the second argument to JSON.parse to do that.
function parseDate(k, v) {
if (k === "time") {
return new Date(v);
}
return v;
}
var json = '{ "name": "Joe", "time": "Sun Apr 26 2015 13:58:54 GMT-0400 (EDT)" }';
var data = JSON.parse(json, parseDate);
console.log(data);