-2

i have a table with a numeric date but I want to change the numeric month into string

<table style="width: 100%;">
    <tr>
        <th>Date</th>
        <th>Total</th>
    </tr>
    <tr>
        <td id="date">2021-11-12</td>
        <td>100</td>
    </tr>
</table>

Now I want to convert it into string just the month name

ex:

<table style="width: 100%;">
    <tr>
        <th>Date</th>
        <th>Total</th>
    </tr>
    <tr>
        <td id="date">November 12, 2021</td> <!---Something like this--->
        <td>100</td>
    </tr>
</table>

is there any way to do that in javascript?

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
Riri
  • 25
  • 5
  • 2
    Does this answer your question? [Convert Date from one format to another format in JavaScript](https://stackoverflow.com/questions/26500694/convert-date-from-one-format-to-another-format-in-javascript) – Pranav Lari Nov 16 '21 at 07:29

4 Answers4

3

Probably you are looking for that?

dt = new Date( "2021-11-12" );
month = dt.toLocaleString('default', { month: 'long' });

console.log(month + ' ' +  dt.getDate() + ', ' + dt.getFullYear())
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
1

Once go through with this npm package

moment().subtract(10, 'days').calendar(); // 11/06/2021
moment().subtract(6, 'days').calendar();  // Last Wednesday at 1:02 PM
moment().subtract(3, 'days').calendar();  // Last Saturday at 1:02 PM
moment().subtract(1, 'days').calendar();  // Yesterday at 1:02 PM
moment().calendar();                      // Today at 1:02 PM
moment().add(1, 'days').calendar();       // Tomorrow at 1:02 PM
moment().add(3, 'days').calendar();       // Friday at 1:02 PM
moment().add(10, 'days').calendar();      // 11/26/2021

https://momentjs.com/ Hope it works for you

1

There are a lot of libraries which provide this functionality. I suggest using Date-fns (https://date-fns.org/) as it uses the native Date type and is fast and reliable.

Using date-fns, you can format the date as follows.

import { format} from "date-fns";

let result = format(new Date("11/12/2021"), "MMMM, dd yyyy"); //November 12, 2021

moment.js (https://momentjs.com/) is also a very popular library but is very big in size and does not work with tree shaking to remove unused functions in the library while building a production website.

Ashwin Valento
  • 878
  • 1
  • 7
  • 14
1
<html>
<body>
<p id="demo"></p>
<script>
var options = { year: 'numeric', month: 'long' ,day: 'numeric' };
var today  = new Date();
document.getElementById("demo").innerHTML = today.toLocaleDateString("en-US", options); 
</script>
</body>
</html>

 

Output will be in the format as November 16, 2021