Converting month number to month name - reactjs

I'm in struggle trying to convert a month number that i'm getting from API to month name and then render the month name in Datatable.
Example:
month (1) => "January"
month (2) => "February"
...etc
For that, i created this function:
function getMonthName(monthNumber) {
const date = new Date()
date.setMonth(monthNumber - 1)
return date.toLocaleString('en-US', { month: 'long' })
}
It works fine if i provide monthNumber correctly.
Now i would like to use this function inside month column (so it will show month names instead of month numbers).
What i'm expecting is: getting different month names at each row successively.
What i'm getting is: table always show January only on all its rows.
I reproduced my issue here:
Sandbox: https://codesandbox.io/s/hopeful-goldberg-xhqvjm-forked-wwq3m0?file=/src/components/tables/SalesTable/SalesTable.jsx

You can use the js-date helper library. I am using date-fns.
Supported formats
npm install date-fns --save
import {format} from 'date-fns'
// Let say its January
const month = 1
// date can be anything
const date = `1970/${month}/07`
const monthName = format(new Date(date), 'LLLL')

Related

Date/Time Formatting in React

I am working with an API that returns Dates in the format 2022-03-01T11:32:37
Created: {this.props.proposal.OPENWHEN}
Created: 2022-03-01T11:32:37
How do i format this into DD/MM/YYY 24:00:00 ?
Thanks In Advance
Something like the following should be enough:
// Example expected argument: 2022-03-01T11:32:37
function prettifyDateTime (str) {
// Splitting the string between date and time
const [date, time] = str.split("T");
// Assuming 03 is the month and 01 is the day – otherwise, those could be swapped
const [year, month, day] = date.split("-")
// Added slashes and the space before the time
return `${day}/${month}/${year} ${time}`
}
prettifyDateTime("2022-03-01T11:32:37") // '01/03/2022 11:32:37'
Otherwise, I recommend using a date library like date-fns, dayJS, or moment.
You can use the Date object to accomplish what you want. It'll also accept other date formats. Here is one place to find Date description. You also get the benefit of rejecting invalid date formats
function prettifyDateTime(str) {
let date = new Date(str);
// There's other ways of formatting this return
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}

Get Integer month and year value in YYYY-MM-DD format from JS date object?

When the user selects from the date field, it is displayed on the screen in the following format.
for example :
moment(Date).format('YYYY-MM-DD')
output=> '2021-10-13'
How can get month(10) and year(2021) values ​​as integer using the ('YYYY-MM-DD') format from above output?
Reference
const d = new Date('2021-10-12')
const year = d.getFullYear()
const month = d.getMonth() + 1
const day = d.getDate()
console.log({year,month,day})

Display rows with current date as top result using react-table

I'm trying to create a table using react-table that would display data that matches today's date as the top result. For instance, today is 18 August 2021, so I would like any data entry that matches 08/18/2021 (mm/dd/yyyy format) to be displayed as the topmost entry in my table.
My current table looks like this
To give an example, I have already sorted my table in chronological order (from earliest to latest in mm/dd/yyyy format). However, I want any entry/entries in the table above with today's date (eg. Date of Operation: 08/18/2021) to be displayed at the top of the table. Thereafter, entries that do not match today's date will continue to be sorted in chronological order.
Can someone please let me know how this can be done? Thank you.
Without getting into the code details, you should be able to do this by supplying a custom sort function in the column definition API docs. We don't do this specific sort but we do have multiple custom sort functions, and I got the most help in writing them by reading the sortTypes.js file from the library source.
Here's a simple date sort function. You basically get two rows and a columnId and return -1, 0, or 1.
const prevDate = new Date(prev.original[columnId])
const prevIsDate = ...
const currDate = new Date(curr.original[columnId])
const currIsDate = ...
if (prevIsDate && currIsDate) {
return prevDate > currDate ? 1 : -1
} else {
if (!prevIsDate) {
return !currIsDate ? 0 : 1
} else {
return 1
}
}
}

How to dynamically get the start and end date of the week

I'm using ionic framework.Is there a way to dynamically get the start and end date of the week when user selects a random date.
Based on this answer I've made a configuration based on your needs. The code is in vanilla js but you can easily translate it to angular code, since functionality is the same.
The function to find the first and last day of the week, based on user selected date:
function getFirstLastDayOfWeek(userDate) {
let result = {};
let curr = new Date(userDate); // get current date
let first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
let last = first + 6; // last day is the first day + 6
result = {
firstDay:new Date(curr.setDate(first)).toUTCString(),
lastDay:new Date(curr.setDate(last)).toUTCString()
};
return result;
};
And here's a working fiddle.
var days=new Date().getWeek();
console.log(days[0].toLocaleDateString() + ' to '+ days[1].toLocaleDateString())
Dynamic date
var days=new Date("10/01/2017").getWeek();
console.log(days[0].toLocaleDateString() + ' to '+ days[1].toLocaleDateString())
Please mention your ionic version.
Using moment.js would solve your problem easily.
Lets say you have a random date with you and wants to find start of week.
moment(<randomDate>).startOf('isoWeek');
End of the week
moment(<randomDate>).endOf('isoWeek');

Angularjs + moments-js returns wrong date

i use angularjs and i want parse a string to a date my code looks like this:
var d=moment.utc("2011-10-02T22:00:00.000Z", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
var year =d.year();
var month =d.month();
var day =d.day();
$log.log("MOMENTS:"+"year: "+year+" month: "+month+" day: "+day);
the date should be "3 october 2011"
but in the log is :MOMENTS:year: 2014 month: 2 day: 6
this date is completly wrong, why is this so and what do i wrong ? i want extract the day, month and year
Here is a fiddle: http://jsfiddle.net/FGa2J/
moment.day() returns the day of the week (not the day of the month) you need moment.date() for that. moment.month() is 0 based, so you will get 9 for October. Also, it seems like moment can parse your date string just fine without specifying the format.
Code from the fiddle:
report ( "2011-10-02T22:00:00.000Z", ["yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"] );
var d = moment("2011-10-02T22:00:00.000Z");
var year = d.year();
var month = d.month();
var day = d.date();
console.log("MOMENTS:"+"year: "+year+" month: "+(month+1)+" day: "+day);
function report( dateString, formats) {
$("#results").append (
$("<li>", { text:
dateString + " is valid: " + moment(dateString, formats).isValid()
})
);
}
You're not using the correct string formatting characters.
You have: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
In moment, it would be: "YYYY-MM-DDTHH:mm:ss.SSSZ"
Note that it's case sensitive, and doesn't necessarily match formats from other languages (.Net, PHP, etc).
However - since this is the ISO-8601 standard format, it is detected and supported automatically. You should simply omit that parameter.
From the documentation:
... Moment.js does detect if you are using an ISO-8601 string and will parse that correctly without a format string.

Resources