htmljquerydateformat

Jquery Reformat date from a string in a tag?


I try to extract and reorganize a date string? 2024-11-21 into 21-11-2024

Any help would be... Helpful :)

Thanks

I have a string in html

<h2 class="tg-item-meta-data tg-element-4">2024-11-21</h2>

I want to display date as 21-11-2024

I tried this to extract number

var number = parseInt(jQuery('.tg-item-meta-data tg-element-4').text()); alert(number);

But fails

How do I extract and reorganize a date string?


Solution

  • You can try like this.

    var dateElement = document.querySelector('.tg-item-meta-data.tg-element-4');
    
    var dateString = dateElement.textContent;
    var dateParts = dateString .split('-');
    
    var result = `${dateParts[2]}-${dateParts[1]}-${dateParts[0]}`;
    
    dateElement.textContent = result;
    <h2 class="tg-item-meta-data tg-element-4">2024-11-21</h2>

    And this is code with jQuery

    $(document).ready(function() {
        var dateString = $('.tg-item-meta-data.tg-element-4').text(); 
    
        var dateParts = dateString.split('-');
        var result = dateParts[2] + '-' + dateParts[1] + '-' + dateParts[0];
    
        $('.tg-item-meta-data.tg-element-4').text(result);
    });