This is my first question in StackOverflow. I'm trying to format a number into date. I get date data like '20210728'
from sql.
So I want to show the date on the web like '2021-07-28'
. I have already made some code to format number into date format, but I want to know if there is any other ways to format data better.
Here is my code:
I'm looking forward to hearing from you. Thanks.
CodePudding user response:
If the format will always be yyyyMMdd
then you could just use a regular expression to add in the dashes if all that you're wanting is to display the date as text. See this regex example for an explanation on how this works: https://regex101.com/r/KGv2iy/1
If you need an actual JS date object, then you could just use that string in a new Date()
call.
Using the Intl.DateTimeFormat
method allows you to do all kinds of formatting on actual Date objects. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
And lastly, but certainly not least, is the moment.js library https://momentjs.com/ that makes it really easy to format your Date objects
const dateNumber = 20210728;
const regex = /(\d{4})(\d{2})(\d{2})/;
const str = dateNumber.toString();
const subst = `$1-$2-$3`;
const dateString = str.replace(regex, subst);
const newDate = new Date(dateString);
const momentDate = moment(dateNumber.toString()).format(`YY-MM-DD`);
console.log({dateString: dateString, newDate: newDate, momentDate: momentDate})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js"></script>
CodePudding user response:
I would suggest to use ExtJs internal methods:
Ext.Date.format(Ext.Date.parse('20210607','Ymd'),'Y-m-d')