A) First of all, your desired date string conversion seems to be easy (solution below) without using any package/overhead.
B) However, if you need to process it further as a JS Date Object, things become more difficult. In this case, I like to provide some useful code snippets at least which might help you depending on your usecase is or what you are aiming for.
A) CONVERSION
Seems you need a simple swap of day and month in your date string? In this case, you do not need to install and import the overhead of a package such as date-fns, moment or day.js. You can use the following function:
const date1 = "16/07/2022"
const date2 = "07/16/2022"
const dateToDateFormat = (date) => {
const obj = date.split(/\//);
return `
{obj[0]}/${obj[2]}`;
};
console.log("New date1:", dateToDateFormat(date1))
console.log("New date2:", dateToDateFormat(date2))
B) STRING TO DATE
Are you using your date results to simply render it as string in the frontend? In this case, the following part might be less relevant. However, in case of processing them by using a JS Date Object, you should be aware of the following. Unfortunately, you will not be able to convert all of your desired date results/formats, here in this case date strings "16/07/2022" & "07/16/2022", with native or common JS methods to JS Date Objects in an easy way due to my understanding. Check and run the following code snippet to see what I mean:
const newDate1 = '07/16/2022'
const newDate2 = '16/07/2022'
const dateFormat1 = new Date(newDate1);
const dateFormat2 = new Date(newDate2);
console.log("dateFormat1", dateFormat1);
console.log("dateFormat2", dateFormat2);
dateFormat2 with its leading 16 results in an 'invalid date'. You can receive more details about this topic in Mozilla's documentation. Furthermore, dateFormat1 can be converted to a valid date format but the result is not correct as the day is the 15th and not 16th. This is because JS works with arrays in this case and they are zero-based. This means that JavaScript starts counting from zero when it indexes an array (... without going into further details).
CHECK VALIDITY
In general, if you need to further process a date string, here "16/07/2022" or "07/16/2022", by converting it to a JS Date Object, you can in any case check if you succeed and a simple conversion with JS methods provides a valid Date format with the following function. At least you have kind of a control over the 'invalid date' problem:
const newDate1 = '07/16/2022'
const newDate2 = '16/07/2022'
const dateFormat1 = new Date(newDate1);
const dateFormat2 = new Date(newDate2);
function isDateValidFormat(date) {
return date instanceof Date && !isNaN(date);
}
console.log("JS Date Object?", isDateValidFormat(dateFormat1));
console.log("JS Date Object?", isDateValidFormat(dateFormat2));
Now, what is the benefit? You can use this function for further processing of your date format depending on what you need it for. As I said, it will not help us too much as we still can have valid date formats but with a falsy output (15th instead of 16th).
CONVERT TO DATE OBJECT BY KNOWING THE FORMAT
The following function converts any of your provided kinds of dates ("MM/DD/YYYY" or "DD/MM/YYYY") to a valid JS Date Object and - at the same time - a correct date. However, drawback is that it assumes to know what kind of input is used; "MM/DD/YYYY" or "DD/MM/YYYY". The dilemma is, that this information is crucial. For example, JS does not know if, for example, "07/12/2022" is "MM/DD/YYYY" or "DD/MM/YYYY". It would return a wrong result.
const newDate1 = "07/16/2022"
const newDate2 = "16/07/2022"
function convertToValidDateObject(date, inputFormat) {
const obj = date.split(/\//);
const obj0 = Number(obj[0])
const obj1 = Number(obj[1])
const obj2 = obj[2]
//
// CHECK INPUT FORMAT
if (inputFormat === "MM/DD/YYYY") {
return new Date(obj2, obj0-1, obj1+1);
} else if (inputFormat === "DD/MM/YYYY") {
return new Date(obj2, obj1-1, obj0+1);
} else {
return "ERROR! Check, if your input is valid!"
}
}
console.log("newDate1:", convertToValidDateObject(newDate1, "MM/DD/YYYY"))
console.log("newDate2:", convertToValidDateObject(newDate2, "DD/MM/YYYY"))
console.log("newDate2:", convertToValidDateObject(newDate2, "MM/YYYY"))
If the wrong format is provided as a second argument, an error is provided in the console. In practise I suggest you to use a try-catch block ( I tried here, but it does not work here in this stackoverflow editor).
I wish you good luck. Hope these information can help you.
Answer from Paul M. on Stack OverflowVideos
It can be done by using following code:
let today = new Date();
let date=today.getDate() + "-"+ parseInt(today.getMonth()+1) +"-"+today.getFullYear();
console.log(date)
The moment library is awesome for all action/formatting that you want to do on date.
Have a look: https://momentjs.com/
You should do something like this:
import * as moment from 'moment'
const yourDate = new Date()
const NewDate = moment(yourDate, 'DD-MM-YYYY')
Date is an object, you cant render it directly in ui, convert the date object to string first. You already imported moment, use the format function, try this:
import React, {PropTypes} from 'react';
import classnames from 'classnames';
import Actions from '../../ actions/statistics';
import Moment from 'moment';
export default class GeneralReport extends React.Component {
render () {
//const { stat } = this.props;
//console.log(this.props.stat)
return (
<div className = "general_report">
<header className = "general_report_head">General Report</header>
<div className="report_dates">
From<span className="number">{Moment(this.props.stat.dateFrom).format('YYYY-MM-DD')}</span>
To<span className="number">{Moment(this.props.stat.dateTo).format('YYYY-MM-DD')}</span>
</div>
<div className="report_main_result"> Total Revenue: <span className="number">{this.props.stat.revenue}</span></div>
<div className="report_main_result"> Total orders: <span className="number">{this.props.stat.order}</span></div>
</div>
);
}
}
Reference: http://momentjs.com/
U can use the Date object method toDateString() also, try this:
<div className="report_dates">
From<span className="number">{this.props.stat.dateFrom.toDateString()}</span>
To<span className="number">{this.props.stat.dateTo.toDateString()}</span>
</div>
This should work and not give you any error.
import React, { PropTypes } from 'react';
import classnames from 'classnames';
import Actions from '../../actions/statistics';
import moment from 'moment';
export default class GeneralReport extends React.Component {
render () {
const { stat } = this.props
const { dateFrom, dateTo, revenue, order } = stat
return (
<div className="general_report">
<header className="general_report_head">
General Report
</header>
<div className="report_dates">
From
<span className="number">
{moment(dateFrom).format('YYYY-MM-DD')}
</span>
To
<span className="number">
{moment(dateTo).format('YYYY-MM-DD')}
</span>
</div>
<div className="report_main_result">
Total Revenue:
<span className="number">
{revenue}
</span>
</div>
<div className="report_main_result">
Total orders:
<span className="number">
{order}
</span>
</div>
</div>
);
}
}