Rendering Date from model in react - reactjs

I am trying to get the date to render in a nice format. currently rendering like this
I tried
function getEndDateFromstring(){
return itinerary.endDate.split('T').slice(-1)[0]
}
then
{itinerary.name} from {getStartDateFromstring()} to {getEndDateFromstring()}
But it is throwing an error
Uncaught TypeError: Cannot read properties of undefined (reading 'split')

This looks like a scope issue, pass the itinerary to your function like below
function getEndDateFromstring(itinerary){
return itinerary.endDate.split('T').slice(-1)[0]
}
and call like
{itinerary.name} from {getStartDateFromstring(itinerary)} to {getEndDateFromstring(itinerary)}

I got it working with this
function addZeroIfOnlyOneChar(dateString){
dateString = String(dateString);
if(dateString.length < 2){
return '0' + dateString
}
return dateString
}
function getDateFromString(dateString){
const date = new Date(dateString)
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${addZeroIfOnlyOneChar(day)}-${addZeroIfOnlyOneChar(month)}-${year}`
}
Thanks Everyone

Related

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

Creating a reusable date formatter in React

I've been struggling to create a reusable function that I can call on dates in my data. The goal is to take any date given, determine if it has just a date, or date and time, then return the data in the appropriate format.
I've been using moment to format things, but am not sure how to actually call this function on the data. I'm very new to React
Here is what I've got so far:
import moment from "moment";
const FormatDate = (dateObject) => {
var dateMutant = dateObject;
var dateMutated = "";
function justDate() {
//formats just a date
dateMutated = moment.utc(dateMutant).format("MM-DD-YYYY");
}
function dateTime() {
//formats a date and time
dateMutated = moment.utc(dateMutant).format("MM-DD-YYYY hh:mm:a");
}
console.log(dateMutated);
return dateMutated;
};
export default FormatDate
I am attempting to call it in a page like this:
React.useEffect(() => {
var testDate = '';
if (allCommentsFetch) {
setAllCommentsLoading(true);
axios
.get(`###API Hook##`)
.then(response => {
let comments = response.data;
comments.forEach(commentfield => {
if (commentfield != null) {
commentfield['commentTimestamp'] = moment.utc(commentfield.commentTimestamp).format('YYYY-MM-DD hh:mm:ss');
testDate = FormatDate(commentfield.commentTimestamp).justDate();
} else {
comments[commentfield] = 'N/A'
}
})
but am getting an error that Object(...)(...).justDate is not a function.
you can write it in a better and cleaner way, first of all, you have not to write your module names in PascalCase, getFormattedName will be a better choice! the second thing is that you are using var... avoid that.
the only thing you have to change in the format function is a format template... and as i see you have only two option (justDate and dateTime) in this case, so let's write it again:
const getFormattedDate = ({ dateObject, includeTime }) => {
const dateFormat = includeTime ? 'MM-DD-YYYY hh:mm:a' : 'MM-DD-YYYY';
return moment.utc(dateObject).format(dateFormat);
};
and about the error you got: (but am getting an error that Object(...)(...).justDate is not a function) the problem is that you didn't return justDate from the FormatDate function.

How to get specific month on AngularJS

How can I get the specific date month coming from the backend on angularJS
I wish to add something like this:
var curMonth = new Date().getMonth();
var monthData = vm.paymentsData[0].date.Date().getMonth();
if (curMonth == monthData) {
console.log ("Same Month");
}
Im getting error on:
var monthData = vm.paymentsData[0].date.Date().getMonth();
it says:
angular.js:14328 TypeError: vm.paymentsData[0].date.Date is not a function
Thanks
Data from the backend
I think your code should be written as follows:
var curMonth = new Date().getMonth();
// this maybe a string .. and you cannot call Date() function in that way.
var monthData = vm.paymentsData[0].date;
// Date function should be called this way.
var monData = (new Date(monthData)).getMonth();
if (curMonth == monData) {
console.log ("Same Month");
}

Cannot read property 'push' of undefined typescript

I am trying to push a date object into an array and I get this error "cannot read property 'push' of undefined".
export class CalendarComponent {
days: Date[]
showMonths() {
const interval = new Interval();
interval.fromMonth = this.selectedFromMonth.number;
interval.fromYear = this.selectedFromYear.number;
interval.toMonth = this.selectedToMonth.number;
interval.toYear = this.selectedToYear.number;
for (let i = interval.fromMonth - 1; i < 11; i++) {
const day = new Date(interval.fromYear, i, 1);
this.days.push(day);
// console.log(day);
// days.push(day);
}
// console.log(day);
}
Why do I get this error if 'days' it is already an array and 'day' it is not undefined ?
You need to initialize your property. You have just set the type of it, but actually it is undefined.
days: Date[] = [];
static typing is typescript future and when you compile your code to javascript typing will gone this just a help to developer during the build time.
days: Date[] is the same you sa days and the initial value is undefined
var days;
console.log(days); // => undefined
that why you need assaign days to [] empty array before you use it
days: Date[] = [];

slice D3 update

I have created a dynamic dropdown who enables to select a country name to see data for this country. When a country is selected a function is invoked that will update the chart with data for this country.
It works well unless I select a country I have already previously selected, in which case I have the following error message:
"Uncaught TypeError: t.slice is not a function"
The dropdown is created and updated with the following code
var countryList = d3.map();
data.forEach(function(d) {
countryList.set(d.country,d.country); });
var select = d3.select(dropdown)
.selectAll("option")
.data(countryList.values().sort())
.enter().append("option")
.attr("value", function(d) {
return [d]; })
.text(function(d) { return [d]; });
d3.selectAll("select")
.on("change",function(){
var selectedCountry = document.getElementById("dropdown");
selectedCountry.options[selectedCountry.options.selectedIndex].selected = true;
var countryName = countryList.get(this.value)
//Calling the function countryChart
countryChart(data,countryName);
});
The function starts with the following code
function countryChart(data,countryName){
dataCou=data.filter(function(d) {
return(d.country == countryName)});
dataCou.forEach(function(d) {
d.monthYear = format.parse(d.monthYear);
d.count =+ d.count;
});
The part of the code that seems to be causing some problem is:
dataCou.forEach(function(d) {
d.monthYear = format.parse(d.monthYear);
d.count =+ d.count;
});
My data are formatted this way:
highest,monthYear,count,country
Community,2011-05-01,1116,Total
Community,2011-06-01,338,Total
Community,2011-07-01,56,Total
Community,2011-08-01,46,Total
Community,2011-09-01,52,Total
Community,2011-10-01,137,Total
Education,2011-05-01,1116,Total
Education,2011-06-01,338,Total
Education,2011-07-01,56,Total
Education,2011-08-01,46,Total
Education,2011-09-01,52,Total
Education,2011-10-01,137,Total
Community,2011-05-01,1116,USA
Community,2011-06-01,338,USA
Community,2011-07-01,56,USA
Community,2011-08-01,46,USA
Community,2011-09-01,52,USA
Community,2011-10-01,137,USA
Education,2011-05-01,1116,USA
Education,2011-06-01,338,USA
Education,2011-07-01,56,USA
Education,2011-08-01,46,USA
Education,2011-09-01,52,USA
Education,2011-10-01,137,USA
Do you have any idea what it is I am doing wrong?
Your d.monthYear is the number for some reason, but must be a string.
d.monthYear = format.parse(d.monthYear); // <-- here is the problem
When I do d3.time.format("%Y-%m-%d").parse(5), I get Uncaught TypeError: t.slice is not a function(…)
But when I do d3.time.format("%Y-%m-%d").parse('2011-05-01'), I get Sun May 01 2011 00:00:00 GMT-0700 (Pacific Daylight Time)

Resources