-3

There is some way that I can format a date inside of a string in js?

like the following string:

"DataEmissao >= 2021-07-01 and DataEmissao < 2021-07-20 and DataVencimento >= 2021-07-01"

I want to format the date from 2021-07-01 to 01/07/2021

Is it possible to do it?

  • Yes. Look at the documentation for [Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) – evolutionxbox Jul 19 '21 at 17:27
  • Hi! Welcome to StackOverflow! Please read our [tour](https://stackoverflow.com/tour) to get a better understanding about how to [ask a good question](https://stackoverflow.com/help/how-to-ask). – 0stone0 Jul 19 '21 at 17:28
  • What do you mean by `DataEmissao >= 2021-07-01 `? or `DataEmissao < 2021-07-20`? – Alireza Ahmadi Jul 19 '21 at 17:29
  • @AlirezaAhmadi DataEmissao is a column in my database, and I'm trying to make a where condiction from a date filter – Célio Junior Jul 19 '21 at 17:31
  • Ok you can compare two date. See https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript – Alireza Ahmadi Jul 19 '21 at 17:33
  • Hello there and welcome to StackOverflow. Try using `replaceAll('-','/')` method to replace `-` with `/`. Now, you just need to find the date string and you are done. – Ariel Jul 19 '21 at 17:34

2 Answers2

1

You will need to extract the date from the string in order to format it, and there are many ways to do that, but it depends on what is consistent in the output. For example, you could use split() or slice(), if you know the date is always the third space separated value, or the date is always starting at a certain character #.

ᴓᴓᴓ
  • 1,178
  • 1
  • 7
  • 18
0

You could use a regex replace.

const str = "DataEmissao >= 2021-07-01 and DataEmissao < 2021-07-20 and DataVencimento >= 2021-07-01";

const fixDates = (str) => str
  .replace(/(\d+)-(\d+)-(\d+)/g, (match, year, month, date) =>
    `${month}/${date}/${year}`);

console.log(fixDates(str));
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132