skip to Main Content

I am retrieving some data from an xml file and wish to split the result, parse it and then print it into an html element.

Here is an example of my xml file:

<Root>
   <Foo>
      <Bar>
         <BarType>Green</BarType>
         <Date>2020-09-03 23:40:55</Date>
      </Bar>
   </Foo>
</Root>

I would like to both split the string from Date and make it more human readable.

so instead of "2020-09-03 23:40:55" it would be "Sept 03, 2020 at 23:40"

Here is my function so far:

function testFoo() {
    $.ajax({
        type: "GET",
        url: "/assets/TestFeed.xml",
        dataType: "xml",
        // Alert if error in reading xml
        error: function (e) {
            alert("An error occurred while processing XML file");
            console.log("XML reading Failed: ", e);
        },
        // Runs if xml read succesully
        success: function (response) {
            
            $(response).find("Foo").each(function () {
                // Finds Date in specific xml node
                var fooDate = $(this).find('Bar:has(BarType:contains("Green")) Date').text();
                
                // Test for console to make sure it works
                console.log(fooDate);
                
                // add to the HTML 
                $("p").append('<span class="date-text">' + "Last Updated:  " + '</span>' + '<span class="date-first">' + fooDate + '</span>' + '<span class="date-time">' + "at " + fooDate + '</span>');
            });
        }
    });
}

2

Answers


  1. If you can use momentjs:

    var response = '<Root>
            <Foo>
            <Bar>
            <BarType>Green</BarType>
            <Date>2020-09-03 23:40:55</Date>
    </Bar>
    </Foo>
    </Root>';
    
    $(response).find("Foo").each(function () {
        var fooDate = $(this).find('Bar:has(BarType:contains("Green")) Date').text();
        
    
        // format date.....
        fooDate = moment(fooDate).format('MMM DD, YYYY \a\t HH:mm');
    
        console.log(fooDate);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
    Login or Signup to reply.
  2. You can use built-in Date constructor:

    new Date("2020-09-03 23:40:55").toLocaleDateString("en");
    // language can be each that browser supports
    

    or

    new Date("2020-09-03 23:40:55").toLocaleString("en"); // whole
    

    or

    new Date("2020-09-03 23:40:55").toLocaleTimeString("en"); // only time
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search