Mongoose - Search dates stored as strings by date range - node.js

I have a mongo db with a paymentDate field stored as strings YYYY-MM-DD (I can't change how these are unfortunately), and I need to do a date range search on them.
I found a post suggesting something like this:
coll.find({paymentDate: new RegExp("^(2016-02-18|2016-06-19)", "i")});
But I can't seem to get that to work at all.
Any help is appreciated, I've hit a dead end here.

Storing dates as strings in YYYY-MM-DD format works fine in this case as the string ordering matches the date ordering so you can do:
coll.find({paymentDate: {$gte: "2016-02-18", $lte: "2016-06-19"}});

Your first objective should be changing the schema and use Date instead of String. But if it's really not possible and you can't think of a really complicated RegEx, you can do it with Javascript using $where, but it's performance will be much slower:
db.test.find({
$where: function () {
var docDate = new Date(this.paymentDate);
return (docDate >= new Date('2016-02-18') && docDate <= new Date('2016-02-19'))
}
})

Related

Trying to delete the date within a range if it matches a variable in Office scripts for Excel

I have a column with dates stored that need to be cleared if they match a variable.
I've tried a ton of different ways, but this is my most recent attempt:
let dateRange = selectedTable
.getColumnByName("Date")
.getRangeBetweenHeaderAndTotal()
.getTexts();
let date: string = "12/2/2022"
console.log(dateRange);
dateRange.forEach(dates => {
if (dates === date){
ExcelScript.ClearApplyTo.contents
}
})
This one won't work as 'dates' is an array and can't be compared to the 'date' variable as far as I can tell.
I think there are two issues you might be running into here:
First: getTexts() returns a 2D array to preserve the row/column structure of the grid. So even though dateRange is a column, it's still a 2D array - something like [['value1'], ['value2'], ...]. You can get a single cell with the expression dateRange[rowIndex][0].
Second: ExcelScript.ClearApplyTo.contents is simply an enum member and does not do anything on its own. To clear the contents of a specific cell/range, you need to call the clear() method on the corresponding Range object.
Putting this together, you get the following script (assuming you've defined selectedTable elsewhere):
let dateRange = selectedTable
.getColumnByName("Date")
.getRangeBetweenHeaderAndTotal();
let texts = dateRange.getTexts();
let date: string = "12/2/2022"
texts.forEach((text, row) => {
if (text[0] === date) {
dateRange.getCell(row, 0).clear();
}
})
Additionally, as pointed out in the comments, you should be careful about date formatting. Since you're comparing strings, this script will fail to clear cells that contain 12/02/2022, December 2, 2022, etc. even though the underlying date is the same.
Hopefully that helps!

Nodejs change time at date type after getting from Mongodb

I wanted to change time at date type which returning from mongodb with custom time like below
"2021-05-26T00:00:00.000Z"
to
"2021-05-26T10:20:00.000Z"
I wanted to change time from a variable at the date, so my technique was split this date with "T" then get time part and change it with custom time
let splitedTime = timev[0].validFrom.toString().split()[0];
let customTime = "10:20:00.000Z";
let finalTime = splitedTime + customTime;
but this split not working this giving me date like this "Wed May 26 2021 06:00:00 GM". Can you please help me for this?
Working with Date
Whilst I understand your logic of converting it to a string and then using string methods to convert it to your desired output, I believe a simpler approach is to use the Date object
function dateAdd(original, hours, minutes) {
const date = new Date(original);
date.setHours(original.getHours() + hours);
date.setMinutes(original.getMinutes() + minutes);
return date.toISOString();
}
When original = "2021-05-26T00:00:00.000Z" then the return value is "2021-05-26T10:20:00.000Z".
If you want a fixed time:
const date = new Date('2021-05-26T00:00:00.000Z');
date.setUTCHours(10);
date.setUTCMinutes(20);
date.setUTCSeconds(0);
date.setUTCMilliseconds(0);
// a cleaner approach:
date.setUTCHours(10, 20, 0); // hoursValue, minutesValue, secondsValue
console.log(date.toISOString());
Which produces the following:
"2021-05-26T10:20:00.000Z"
Another Solution
Your actual problem is being caused by the fact you call toString which returns a date string in the format of "Tue Aug 19 1975 23:15:30 GMT+0200 (CEST)" so when you're splitting by "T", that's way down at the end. toISOString will return the correct format.
Explanation
As you can see above, we avoid using string methods and use the methods that exist on Date. This approach is safer as you avoid issues with the difference between toISOString and toString. You may also find moment useful if you're using dynamic methods of changing dates regularly.
Note
In all honesty, I'm not entirely sure I understand the why behind what you're doing, so if I'm wrong please correct me so I can update my answer to be more relevant for you.
Learn More
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

how to compare dates using relational Operators in dart?

I'm working on a problem which requires to compare the date with other if the selected date is less than given then print Hello.
The date is present In String Format like given in Examaple
Ex:
if('2020-1-13'<'2021-1-5')
{
print(hello);
}
You should try this it should work
````
var date1 = DateTime.parse('2020-01-13').millisecondsSinceEpoch.toInt();
var date2 = DateTime.parse('2021-01-15').millisecondsSinceEpoch.toInt();
if(date1 < date2){
print('true');
}else{
print('false');
}
````
Instead of doing that just use the date's isBefore or isAfter operator
It would look something like the following:
final now = DateTime.now();
final yesterday = DateTime.now().subtract(Duration(days: 1));
print(now.isAfter(yesterday)); //true
Since your dates are in STring format, it you would have to use the DateTime.parse() method to construct your date objects, and then use the operators talked about above
package:basics provides DateTime extensions that can easily compare DateTime objects.
(Disclosure: I contributed those particular extensions.)

Moment.js failed to valid time when passing date

I'm reading values from an old csv file that I have. This file has a lot of wrong data, it should has only time values, but sometimes it has date values on it.
I'm trying to valid time with moment.js, but when I run this code:
const moment = require('moment');
console.log(moment('19/07/9130','hh:mm').isValid());
It returns true, I'm doing something wrong??
1.
First of all, you are giving wrong format in moment function, you are passing data in DD/MM/YYYY format and defining format hh:mm. You should pass correct format.
2.
19/07/9130 is valid date which have year 9130 and it's absolutely valid future year. If you want to restrict maximum year, you can use isBefore method
var mydate = moment('19/07/9130', 'DD/MM/YYYY');
var isValid = mydate.isValid() && mydate.isBefore('2050-01-01');
Reading more the Moment.js docs, I find a third parameter that make Moment use strict parsing.
const moment = require('moment');
console.log(moment('19/07/9130','hh:mm',true).isValid());
This works fine!

Static chart with timestamp on x-axis

I want to create a static chart of values pulled out of a MySQL database.
The chart format would be (x axis : dd/mm/yy hh:mm:ss (corresponding to timestamp of mysql database)) and y-axis would be a double value. I am able to successfully retrieve these values from MySql database.I want help plotting them by ZingChart
Nikita.
Once you've retrieved your values from your MySQL database, you'll want to convert the MySQL date values in to Unix time in milliseconds. I've populated a $date array with the MySQL date values, and iterated over the array, calling strtotime to first convert to Unix time, and multiplying by 1000 to convert to milliseconds. In order to be able to directly modify array elements within the loop, I've also preceded $value with to assign by reference.
foreach ($date as &$value){
$value = strtotime( $value ) * 1000;
}
So now that the values in the $date array have been converted to the proper format, it's time to create a JavaScript array from the PHP array. This can be done using join():
var dateValues = [<?php echo join($date, ',') ?>];
The resulting array looks like this:
var dateValues = [1356994800000,1357081200000,1357167600000, ... ];
To use this array in ZingChart, use the dateValues variable with "values" in the scale-x object. To convert the Unix time values back to dates in ZingChart, add the "transform" object, and set it to "type":"date".
"scale-x":{
"values": dateValues,
"transform":{
"type":"date",
"item":{
"visible":false
}
}
},
...
That takes care of the scale. To get your other values in the chart, you do pretty much the same thing. Convert the PHP arrays into JavaScript arrays, and use the array variable in your chart JSON.
With the PHP $series array:
var seriesValues = [<?php echo join($series, ',') ?>];
In your chart JSON:
"series":[
{
"values":seriesValues
}
]
I've compiled all of this in to a Github Gist for you. Let me know if you have any questions!
Check out our demos repo on GitHub. We have a tutorial specifically about connecting to a MySQL database with PHP.
There's a step-by-step walkthrough on our site, too.
If you share your JSON or more details about it, I can help you with putting your chart together.
I'm on the ZingChart team. Please let me know if you have other questions.

Resources