Why is date-fns isAfter and isBefore both false? - reactjs

I have my current date as
const currentDate = format(new Date(2021, 4, 5), 'yyyy-MM-dd');
Which displays
Current Date is: 2021-05-05
Then I have "Manchester's game is ", formatDate('2021-05-04T14:00:00')
The formatDate function is
const formatDate = (date) => {
return format(new Date(date), 'yyyy-MM-dd');
};
Which displays Manchester's game is 2021-05-04
When I compare the two times using isAfter and isBefore, I get false for both.
I am expecting this
console.log(isAfter(currentDate, formatDate('2021-05-04T14:00:00')));
To log true, but it logs false!
Why is that?

The argument type of isAfter is Date | Number, but you put in string type (your formatDate function return string, and currentDate is also string), so it will not work.
const currentDate = new Date(format(new Date(2021, 4, 5), 'yyyy-MM-dd'));
const comparedDate = new Date(format(new Date('2021-05-04T14:00:00'), 'yyyy-MM-dd'));
console.log(currentDate); // Date type
console.log(comparedDate); // Date type
console.log(isAfter(currentDate, comparedDate)); // True

Related

How to generate array of string with the weekdays from the current weekday using moment

Want to generate the dynamic array of string with the weekdays as a value inside the array for the list which I am using.
Required:=> If current weekday is Monday then array should be
['today','tomorrow','Wednesday','Thursday','Friday','Saturday','Sunday']
Array should be dynamic based on the current day.
To generate array with the weekday as a string here is the code.
const daysArray = () => {
const weekArray = [...Array(7 - moment().weekday())];
const today = new Date();
return weekArray.map((week, index) => {
const dayName = moment(today)
.add(index, "days")
.calendar()
.split(" at")[0];
const date = moment(today).add(index, "days").format(DATE_FORMAT);
return { value: dayName, name: dayName, date };
});
};
This will generate the array of object with dynamic weekdays inside it. If you will return only dayName then you'll get you're desired result.

Define type for date component in typescript

Since I am new to typescript , can you please suggest me how can i define type for my date component (separator='')
export function getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
Thats how you define this function in typescript
export function getCurrentDate(separator: string = ''): string{
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
You can omit the type definition of the separator, typescript will automatically bind a type string to the separator since it has a default value of a string in an operation known as type inference, you can read more about type inference here

React - convert date with date-fns

I have a date in this format: 12-21-2021
This date comes from a Redux selector.
So console.log('ccc', lastUpdateDate); at the beginning shows only:
ccc
and after few times shows
ccc 12-21-202
If I use new Date(lastUpdateDate).toDateString() it turns out it works only in Chrome, whereas FireFox and Safari say this is an invalid date.
So I want to convert it in the right way using a function.
So I created this function:
const parseDateWithDashes = (dateToParse) => {
console.log('dateToParse', dateToParse);
useEffect((): any => {
let finalDate;
dateToParse instanceof Date && dateToParse.getTime()
? (finalDate = format(dateToParse, "yyyy-MM-dd'T'HH:mm:ss.SSSxxx"))
: null;
console.log('finalDate', finalDate);
return finalDate;
}, [dateToParse]); //since at the beginning it is empty, it should re-run as a date is available
};
parseDateWithDashes(lastUpdateDate)
However doing this it logs out:
dateToParse (several time empty)
dateToParse 12-21-2021
finalDate undefined (several times)
I've also tried to run the function in a useEffect...
useEffect(() => {
parseDateWithDashes(lastUpdateDate);
});
But that's an invalid hook call.
What am I doing wrong? How to fix that?
I resolved it this way.
I added the parsing to the thunk. And stringified in order to avoid non-serialized errors:
const parsedDate = parse(lastUpdateDate, 'MM-dd-yyyy', new Date());
dispatch(setLastUpdateDate(JSON.stringify(parsedDate)));
Then I just formatted it in the component:
export const convertStringDateToDate = (date: string) => {
let finalDate;
try {
finalDate = JSON.parse(date);
finalDate = format(parseISO(finalDate), 'E LLL d yyyy');
} catch (e) {
finalDate = 'loading date';
}
return finalDate;
};
That works

Convert datetime to timestamp milliseconds adding +1 month

high chart not rendering in IE and Safari, and solution for this problem is converting my date from API to time stamp in milliseconds.
here is code for convert
var date = '2017-06-07 10:00:00'
var d = date.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/)
console.log(d)
var parsed = +(new Date(d[1], d[2], d[3], d[4], d[5], d[6]).getTime())
console.log("timestamp: " + parsed) // 1499414400000 ==> July 7, 2017 8:00:00 AM
But I allways get +1 month
here is example
js fiddle
This is because the moth count start with zero you can see here the full explanation:
https://www.w3schools.com/jsref/jsref_getmonth.asp
Hello Please check it out this can be your perfect solution
const date = '2017-06-07 10:00:00'
const d = date.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/)
var dates = new Date(d[0])
const parsed = new Date(dates).getTime()
Highcharts.stockChart('container', {
series: [{
data: [[parsed, 10]]
}]
});
thnx to all, here is how I fix this.
var date = '2017-06-07 10:00:00'
var d = date.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/)
var parsed = new Date(d[1], d[2]-1, d[3], d[4], d[5], d[6]).getTime() //I added -1 for month
Highcharts.stockChart('container', {
series: [{
data: [[parsed, 10]]
}]
});

How to get data from mongoDB based on date from express.?

I am trying to get data from mongoDB collection based on the date it is created.
Date format using to get data: yyyy-mm-dd (eg: 2015-04-14)
Format saved in collection : timestamp: "2015-04-13T17:50:48.761Z"
Controller :
$scope.getExpences = function (date) {
SelectedMemberExpence.get( date )
.success(function (result) {
$scope.allExpences = result;
})
}
Service :
.service('SelectedTimeExpence', function ($http) {
return {
get : function(datetime) {
return $http.get('/api/expences/'+ datetime);
},
delete : function(datetime) {
return $http.delete('/api/expences/'+ datetime);
}
}
})
Express code :
router
.param('datetime', function (req, res, next) {
req.dbQuery = { timestamp : req.params.datetime };
next();
})
.route('/expences/:datetime')
.get(function (req, res) {
var collection = db.get('memberExpences');
collection.find(req.dbQuery , function (err, data) {
res.json(data);
});
});
I know, I am doing something wrong in 'express' code function. Please help anyone to resolve this problem.
The timestamp field in your collection is of string type which resembles an ISO date timestamp string. The query will certainly not work because you will be comparing two completely different strings (based on length, the timestamp field has more characters than the datetime req parameter value).
Would be much easier if you were to include another field in your document schema that actually represents a date:
db.collection.find().forEach(function (doc){
doc.created_on = ISODate(doc.timestamp);
db.collection.save(doc);
});
You can then use a range query to search for documents whose value for the created_on field is greater than a Date object representing the start of the datetime variable day, and less than a Date object representing the datetime variable day end.
First you need to construct the Date objects representing the start and end of the datetime day. For example:
var datetime = "2015-04-14",
start = new Date(datetime),
dateParts = datetime.split('-'),
y = parseInt(dateParts[0], 10),
m = parseInt(dateParts[1], 10),
d = parseInt(dateParts[2], 10),
end = new Date(y, m-1, d+1);
console.log(start.toISOString()); // "2015-04-14T00:00:00.000Z "
console.log(end.toISOString()); // "2015-04-15T00:00:00.000Z"
In your Express code you can then modify it to reflect the above:
router
.param('datetime', function (req, res, next) {
var start = new Date(req.params.datetime),
dateParts = datetime.split('-'),
y = parseInt(dateParts[0], 10),
m = parseInt(dateParts[1], 10),
d = parseInt(dateParts[2], 10),
end = new Date(y, m-1, d+1);
req.dbQuery = {"created_on": { $gte: start, $lt: end }};
next();
})
.route('/expences/:datetime')
.get(function (req, res) {
var collection = db.get('memberExpences');
collection.find(req.dbQuery , function (err, data) {
res.json(data);
});
});
Note the use of the special $ operators, $gte (greater-than-or-equal) and $lt (less-than), which are used to perform a range query to get the matching documents.
Using MomentJS:
var start = moment("2015-04-14").format();
var end = moment(start).add('days', 1);
db.collection.find({"created_on": {"$gte": start, "$lt": end}});
EDIT
In node, the Mongo driver will give you an ISO string, not the object thus if you want to include an additional created_on field in your document, simply add a new field with the current date value. For example:
.post(function (req, res) {
var date = new Date();
var expence = req.body;
expence["created_on"] = date;
var collection = db.get('memberExpences');
collection.insert(expence, function (err, data) {
res.json(200);
});
});
A little change I had to use with the above answer that I want to share with you
var start = moment("2020-04-14").format();
db.collection.find({"created_on": {"$gte": new Date(start)}});

Resources