Sorting array by date and time in same time? - javascript

I am building shedule app, so i need to sort items by date and time in same time. Like you see in example i can only filter hours and minuts and that works, but i need to filter dates too
I am storing date in datebase like YYYY-MM-DD and time by hours and minuts like string for example: hours:"08",minuts:"25".
this.ord3ref.on("child_added", data => {
this.ord3.push({
key: data.key,
data: data.val()
});
this.ord3.sort(
(a, b) => a.data.hours- b.data.hours || a.data.minuts- b.data.minuts
);
});
like you see on image it sorts array by hours and minuts, but its need to be sorted by dates first, than with hours and minuts...

If the data contains a key/value for date then you should be able to just substitute your sort function with this:
this.ord3.sort(
(a, b) => {
var dateA = new Date(a.data.date).valueOf();
var dateB = new Date(b.data.date).valueOf();
return a.data.hours - b.data.hours || a.data.minuts - b.data.minuts || dateA - dateB;
}
);
javascript Date objects can be created from the date strings in the format YYYY-MM-DD.
The .valueOf() method returns the number of milliseconds from UTC time - see MDN's explanation of it.

Related

Javascript - Operator '>' cannot be applied to types 'Date' and 'Moment'

I want to compare last 30 mins data and display in UI. Datetime needs be UTC. I tried using Moment but i am getting error
Javascript - Operator '>' cannot be applied to types 'Date' and 'Moment'.
Below is my code :
let d = moment();
let d_utc = moment.utc();
var customDate = new Date();
d_utc.minutes(-30);
filteredData = filteredData.filter((category) => {
return category.uploaded_time > d_utc;
});
If you wish to compare a Date to an instance of a Moment with a Date, you need to convert them both to the same date.
You can call .toDate() to convert a moment to a Date or moment(date) to convert a Date to a Moment.
return category.uploaded_time > d_utc.toDate()
JavaScript doesn't have operator overrides, so the safest way to compare Moments is using diff:
return moment(category.uploaded_time).diff(d_utc) > 0
At the documentation in get+set section you can compare the seconds
Examplet in documentation
moment.utc().seconds(30).valueOf() === new Date().setUTCSeconds(30);
Your code should be
let d_utc = moment.utc();
let d_utc = moment.utc().minutes(-30).valueOf();
filteredData = filteredData.filter((category) => {
return category.uploaded_time.getUTCSeconds() > d_utc;
});
Also there is a query section you can check it

How to format a date received from my server using javascript?

I need to format a date with javascript but I'm having a little trouble solving this.
I get two dates, I need to format them and then join the values.
On one of the dates I get this:
"2022-07-12T04:00:00-0300"
And on the other date I get this:
"2022-07-12T06:00:00-0300"
These are always dynamic dates returned from my backend, but here on the frontend I need to display these two dates in this following format:
"04:00 - 06:00"
This is assuming you only need the hours and minutes.
function datesToRange(start, end) {
if (!start || !end) return ""; // If either date is null or undefined.
return start.substring(12, 17) + " - " + end.substring(12, 17);
}
Now you can call this method to get the range in your required format.
E.g.
datesToRange("2022-07-12T04:00:00-0300", "2022-07-12T06:00:00-0300");
Will return "04:00 - 06:00".
You can use slice() method.
var date1 = "2022-07-12T04:00:00-0300";
var date2 = "2022-07-12T06:00:00-0300";
var formatted = `${date1.slice(11, 16)} - ${date2.slice(11, 16)}`;
console.log(formatted);

How to get a string of max date from an array of string dates?

What would be the most elegant way to get max date from an array of strings like below?
var dates = ["2018-12-29T15:23:20.486695Z", "2018-12-29T15:23:21.613216Z", "2018-12-29T15:23:22.695710Z", "2018-12-29T15:23:24.013567Z", "2018-12-29T15:23:25.097649Z", "2018-12-29T15:23:26.692125Z", "2018-12-29T15:23:27.918561Z", "2018-12-29T15:23:29.217879Z", "2018-12-29T15:23:30.468284Z", "2018-12-29T15:23:31.548761Z"]
I have tried:
var timestamps = dates.map(date => Date.parse(date));
var max_date = Math.max.apply(Math, timestamps)
But this leaves me with a timestamp that I would need to convert back to the exact original format (and I don't know how to do that).
​
You could compare the ISO 8601 date like strings and take the greater value.
var dates = ["2018-12-29T15:23:20.486695Z", "2018-12-29T15:23:21.613216Z", "2018-12-29T15:23:22.695710Z", "2018-12-29T15:23:24.013567Z", "2018-12-29T15:23:25.097649Z", "2018-12-29T15:23:26.692125Z", "2018-12-29T15:23:27.918561Z", "2018-12-29T15:23:29.217879Z", "2018-12-29T15:23:30.468284Z", "2018-12-29T15:23:31.548761Z"],
latest = dates.reduce((a, b) => a > b ? a : b);
console.log(latest);
That's the format provided by toISOString on Date. So you take your timestamp value, feed it into new Date, and use toISOString on the result:
console.log(new Date(max_date).toISOString());
Example:
var dates = [
"2018-12-29T15:23:20.486695Z",
"2018-12-29T15:23:21.613216Z",
"2018-12-29T15:23:22.695710Z",
"2018-12-29T15:23:24.013567Z",
"2018-12-29T15:23:25.097649Z",
"2018-12-29T15:23:26.692125Z",
"2018-12-29T15:23:27.918561Z",
"2018-12-29T15:23:29.217879Z",
"2018-12-29T15:23:30.468284Z",
"2018-12-29T15:23:31.548761Z"
];
var timestamps = dates.map(date => Date.parse(date));
var max_date = Math.max.apply(Math, timestamps)
console.log(new Date(max_date).toISOString());
Note that you get "2018-12-29T15:23:31.548Z" rather than "2018-12-29T15:23:31.548761Z" because you've parsed the strings to JavaScript dates, and JavaScript dates only hold milliseconds, not microseconds.

Javascript Cannot use .now() on date string

So I wanted to compare two dates inside a post object. I tried to compare the date objects, but that returned NaN. Then I tried converting it to milliseconds since 1970 by using .now() on these dates, but it returned the following error:
It happens: TypeError: a.date.now is not a function
I tried typeof a.date and this returned string. I don't know why I can't use the .now() method. Can someone help me?
the whole function inside of angular service
getPosts(section) {
return this.http.get(url + '/forum/getPosts/' + section )
.map( (posts: any) => {
// posts should be ordened based on latest replies. If there are no replies yet, we compare it to the date
// of the original post
posts.obj.sort((a, b) => {
const aHasReplies = a.replies.length !== 0;
const bHasReplies = b.replies.length !== 0;
if (aHasReplies && bHasReplies ) {
return a.replies.slice(-1, 1)[0].date - b.replies.slice(-1, 1)[0].date;
} else if ( aHasReplies && !bHasReplies) {
return a.replies.slice(-1, 1)[0].date - b.date;
} else if ( !aHasReplies && bHasReplies) {
return a.date - b.replies.slice(-1, 1)[0].date;
} else {
console.log(a.date.now());
return a.date - b.date;
}
});
return posts;
});
}
It should be object, not string, if that's what you meant, because there is no "date string".
Other than that try:
new Date(a.date).getTime()
Because .now is a static method, you always use it as Date.now()
This means, that Date.now() always returns milliseconds elapsed since the UNIX epoch.
For converting to unix time use getTime.
If you want to compare them, compare two dates without conversion.
But keep in mind, that unix time is in seconds, and javascript method return in milliseconds. If you need exactly unix time, divide by 1000.
You can compare two dates in the year-month-day format (yyyy-mm-dd) using regular javascript comparators such as < and > etc
I suggest use moment.js library (https://momentjs.com/docs/) to parse Date from String.
So you can have some thing like
let date = moment(a.date)

Date String sorting in trNgGrid

My column contains a list of dates in string format. Eg.: "Aug 2013", "Sep 2012" etc
But when I try to sort, it sorts alphabetically. One approach I thought of was to convert it to epoch format by using javascript.
new Date("Aug 2013").getTime()
This returns a long value in epoch format 1375295400000 and I believe I can sort it then.
I have trouble integrating it in the frontend code. Is there any way I can achieve this?
To sort your list of dates (in string format), you can use the sort function with a custom comparison function. This comparison function converts the two strings to date objects then to millisecond and returns the difference.
var list = ["Aug 2013", "Sep 2012", "Sep 2010"];
var sli = list.sort(function (a, b) {
var d1 = new Date(a).getTime();
var d2 = new Date(b).getTime();
return d1 - d2;
});
res.end('sli='+sli);
Output:
sli=Sep 2010,Sep 2012,Aug 2013
Alright the fix was pretty simple. I passed the UTC time format in JSON data as utcTime. Hence in the TrNgGrid column declaration
field-name="utcTime" display-format="displayTimePeriod:gridItem"
And in the angular module define displayTimePeriod filter as
.filter("displayTimePeriod", function() {
return function(fieldValueUnused, item) {
return item.timePeriod;
}
})
So sorting happens based on utcTime variable but in the view I have timePeriod displayed.

Categories

Resources