Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    New Coder
    Join Date
    Dec 2012
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Auto-Editing XML Node Value - Make timestamp readable

    Greetings all,

    I have an issue where I am having trouble converting a timestamp into a readable value. These timestamp values are external and I need a simple way to either:

    a) Convert it into a readable format (ie. December 16th, 8:54pm)

    b) Strip the middle of the data from the node (ie. <Created>2012-12-07T23:22:11.822Z</Created> = strip after 'T' until '.' to just acquire the time (ie. 23:22:11) )

    Here is the code I'm initially pulling the data with:

    Code:
    var i=0,d;
    while (d=document.getElementById("Created"+i)) d.innerHTML=xmlDoc.getElementsByTagName("Created")[i++].childNodes[0].nodeValue;
    Here is what the node looks like:

    Code:
    <Created>2012-12-07T23:22:11.822Z</Created>
    And here is how it's posted:

    Code:
    <div id="fitin">
    <span id="Body0"></span>
    </div>
    I suppose I need a script to either convert it into words (ie. December 16th, 8:45pm) or if that's too hard, just pull everything inbetween 'T' and '.' so that I can at least get an accurate time. This is for a large scale LCD that displays real time information.

    Any help is appreciated!

  • #2
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Use the nodeValue to create a JavaScript Date:

    Code:
    var xmlDate = new Date('2012-12-07T23:22:11.822Z'); // from the nodeValue
    var jsDate = xmlDate.format('mmmm dxx, h:nnap');
    alert(jsDate); // December 7th, 11:22pm
    Code:
    Date.prototype.format = function (sFormat, twelve) {
        // Returns: A string version of the date.
        // Usage: date_instance.format("d mmm yy hh:nn:ss ap") or 
        // date_instance.format("dddd dd mmmm hh:nn", true)
        // Defaults to YYYY/MM/DD.
        // twelve == true for a 12hr clock, or just AP or ap within 
        // sFormat (for AM/PM or am/pm).
        // Use z or zzz for milliseconds and xx for suffixes (st, nd, etc.).
        var MonthNames = ["January", "February", "March", "April", "May", "June", 
            "July", "August", "September", "October", "November", "December"];
        var DayNames = [ "Sunday", "Monday", "Tueday", "Wednesday", "Thursday", 
            "Friday", "Saturday" ];
        var dDate = this || new Date(),
            D = dDate.getDate(), DDDD = DayNames[dDate.getDay()], 
            DDD = DDDD.substr(0,3),
            M = dDate.getMonth()+1, MMMM = MonthNames[dDate.getMonth()], 
            MMM = MMMM.substr(0,3),
            YYYY = dDate.getFullYear(), YY = ('' + YYYY).substr(2, 2),
            H = dDate.getHours(), N = dDate.getMinutes(), S = dDate.getSeconds(),
            Z = dDate.getMilliseconds(),
            ap = (H > 11) ? "pm" : "am",
            // pad with leading zeros, if required
            DD = ( D < 10 ? "0" : "" ) + D,
            MM = ( M < 10 ? "0" : "" ) + M,
            NN = ( N < 10 ? "0" : "" ) + N, 
            SS = ( S < 10 ? "0" : "" ) + S,
            ZZZ = ( Z < 10 ? "00" : (Z < 100 ? "0" : "") ) + Z, XX;
        var AP = (sFormat && (sFormat.toUpperCase().indexOf('AP')+1)) ? 
            ((sFormat.indexOf('ap')+1) ? ap : ap.toUpperCase()) : '';
        if (twelve || AP) {
            H = (H < 12) ? (H || 12) : ((H - 12) || 12);
        }
        var HH = ( H < 10 ? "0" : "" ) + H;
        XX = (D == 1 || D == 21 || D == 31) ? "st" : 
            ((D == 2 || D == 22) ? "nd" : ((D == 3 || D == 23) ? "rd" : "th"));
        sFormat = ( sFormat ) ? sFormat.toUpperCase() : 'YYYY/MM/DD';
        var sParsed = sFormat.replace(/D{1,4}|M{1,4}|Y{2,4}|H{1,2}|N{1,2}|S{1,2}|Z{1,3}|XX|AP/g,
            function (m) {
                try {
                    return eval(m);
                } catch (e) {
                    return '';
                }
            });
        return sParsed;
    };
    [Anticipating comments.. I could rewrite this to not use eval() but I believe it to be a legitimate (or, at least, acceptable) use in this specific context.]
    Last edited by AndrewGSW; 12-10-2012 at 08:09 PM.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #3
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Here's a complete page for testing.

    Code:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Page Title</title>
    
    <script>
    Date.prototype.format = function (sFormat, twelve) {
        // Returns: A string version of the date.
        // Usage: date_instance.format("d mmm yy hh:nn:ss ap") or 
        // date_instance.format("dddd dd mmmm hh:nn", true)
        // Defaults to YYYY/MM/DD.
        // twelve == true for a 12hr clock, or just AP or ap within 
        // sFormat (for AM/PM or am/pm).
        // Use z or zzz for milliseconds and xx for suffixes (st, nd, etc.).
        var MonthNames = ["January", "February", "March", "April", "May", "June", 
            "July", "August", "September", "October", "November", "December"];
        var DayNames = [ "Sunday", "Monday", "Tueday", "Wednesday", "Thursday", 
            "Friday", "Saturday" ];
        var dDate = this || new Date(),
            D = dDate.getDate(), DDDD = DayNames[dDate.getDay()], 
            DDD = DDDD.substr(0,3),
            M = dDate.getMonth()+1, MMMM = MonthNames[dDate.getMonth()], 
            MMM = MMMM.substr(0,3),
            YYYY = dDate.getFullYear(), YY = ('' + YYYY).substr(2, 2),
            H = dDate.getHours(), N = dDate.getMinutes(), S = dDate.getSeconds(),
            Z = dDate.getMilliseconds(),
            ap = (H > 11) ? "pm" : "am",
            // pad with leading zeros, if required
            DD = ( D < 10 ? "0" : "" ) + D,
            MM = ( M < 10 ? "0" : "" ) + M,
            NN = ( N < 10 ? "0" : "" ) + N, 
            SS = ( S < 10 ? "0" : "" ) + S,
            ZZZ = ( Z < 10 ? "00" : (Z < 100 ? "0" : "") ) + Z, XX;
        var AP = (sFormat && (sFormat.toUpperCase().indexOf('AP')+1)) ? 
            ((sFormat.indexOf('ap')+1) ? ap : ap.toUpperCase()) : '';
        if (twelve || AP) {
            H = (H < 12) ? (H || 12) : ((H - 12) || 12);
        }
        var HH = ( H < 10 ? "0" : "" ) + H;
        XX = (D == 1 || D == 21 || D == 31) ? "st" : 
            ((D == 2 || D == 22) ? "nd" : ((D == 3 || D == 23) ? "rd" : "th"));
        sFormat = ( sFormat ) ? sFormat.toUpperCase() : 'YYYY/MM/DD';
        var sParsed = sFormat.replace(/D{1,4}|M{1,4}|Y{2,4}|H{1,2}|N{1,2}|S{1,2}|Z{1,3}|XX|AP/g,
            function (m) {
                try {
                    return eval(m);
                } catch (e) {
                    return '';
                }
            });
        return sParsed;
    };
    
    var xmlDate = new Date('2012-12-07T23:22:11.822Z');
    var jsDate = xmlDate.format('mmmm dxx, h:nnap');
    alert(jsDate); // December 7th, 11:22pm
    
    </script>
    </head>
    <body>
    <h1>Just a Heading</h1>
    
    </body>
    </html>
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #4
    New Coder
    Join Date
    Dec 2012
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Greetings,

    The way the code looks and displays is beautiful =D

    I suppose the issue I'm encountering is that I need to be able to run that script over every instance of:

    Code:
    <Created>2012-12-07T23:22:11.822Z</Created>
    There are 5 instances of this that are pulled from an external XML file and they correspond directly with other posts I have:

    Code:
    <span id="Body0"></span>
    Essentially I want to be able to do something of this nature:

    Code:
    <span id="Timestamp0"></span>
    <span id="Body0"></span>
    <span id="Timestamp1"></span>
    <span id="Body1"></span>
    <span id="Timestamp2"></span>
    <span id="Body2"></span>
    ....etc
    So, in short, the way it displays looks wonderful but I need to be able to have that script apply to any node pulled with the name "Created", then call it using a span.

    Any help is appreciated!

  • #5
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    then call it using a span..??
    Do you mean: insert into existing spans or create new spans? If I assume the 2nd of the these and that the posts have tag-name 'Post', then it might be something like this:

    Code:
    var i, creates = xmlDoc.document.getElementsByTagName('Created');
    var xmlPosts = xmlDoc.document.getElementsByTagName('Post');
    // I assume the posts are of the same length?
    var createsLen = creates.length;
    var frag = document.createDocumentFragment(), spanT, spanB, theStamp;
    for (i=0; i < createsLen; i++) {
        spanT = document.createElement('span');
        spanB = document.createElement('span');
        spanT.id = 'Timestamp' + i;
        spanB.id = 'Body' + i;
        frag.appendChild(spanT);
        frag.appendChild(spanB);
        theStamp = creates[i].childNodes[0].nodeValue;
        theStamp = new Date(theStamp);
        theStamp = theStamp.format("mmmm dxx, h:nnap");
        spanT.innerHTML = theStamp;
        // ..or use createTextNode()
        spanB.innerHTML = xmlPosts[i].childNodes[0].nodeValue;
    }
    document.body.appendChild(frag);
    // ..or append to some other element.
    or, in TechniColor
    Attached Thumbnails Attached Thumbnails Auto-Editing XML Node Value - Make timestamp readable-techni.png  
    Last edited by AndrewGSW; 12-11-2012 at 07:10 PM.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #6
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Code:
    <span id="Body0"></span>
    If these spans already exist then you'll need to loop through them using insertBefore() to insert the timestamps.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #7
    New Coder
    Join Date
    Dec 2012
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Greetings Andrew,

    I appreciate all of the help. So here is a breakdown of how I have it as of now:

    Code:
    <span id="Body0"></span>
    <span id="Body1"></span>
    <span id="Body2"></span>
    etc...
    
    <script>
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.open("GET","secretlink=xml",false);
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;
    
    var i=0,d;
    while (d=document.getElementById("Body"+i)) d.innerHTML=xmlDoc.getElementsByTagName("Body")[i++].childNodes[0].nodeValue;
    </script>
    And here is small sample of the XML file I'm pulling the data from:

    Code:
    <PostItems>
          <member>
            <Author>user:chayavic</Author>
            <Body>@joelboss just saved someone's Christmas. What have you done today? There's still time. #c2alerts</Body>
            <Topics>
              <member>hashtag:c2alerts</member>
              <member>user:joelboss</member>
            </Topics>
            <Created>2012-12-12T23:41:50.948Z</Created>
            <Votes>
              <DownVotes>0</DownVotes>
              <UpVotes>2</UpVotes>
              <UpVoters>
                <member>
                  <Timestamp>2012-12-12T23:49:22.789Z</Timestamp>
                  <Voter>user:snyderm</Voter>
                </member>
                <member>
                  <Timestamp>2012-12-13T00:17:28.380Z</Timestamp>
                  <Voter>user:amyschra</Voter>
                </member>
              </UpVoters>
            </Votes>
            <PostId>da3316a1-bdda-40c6-8429-5d694ca6ecd3</PostId>
          </member>
    I don't know what exactly I'm doing wrong, but essentially I'm pulling "Body" Data with the code into an array, and somehow I need to pull the "Created" info (converted into format Tuesday, December 16th 8:55pm)

    I've tried the code you suggested and been smashing my head against the wall trying to figure out what I'm doing wrong.


    Oh, and for clarification, the code should essentially create the spans "Created0", "Created1", etc. It already extracts the Body data, which was pretty simple because I'm not editing it at all.

    I wish I had a Live version to show you but everything on internal on the server here. You wouldn't have access unless you were on the VPN.

  • #8
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Something like:

    Code:
    var i = 0, d, xmlBodyN, xmlCreate, newCreate, jsDate;
    
    while (d = document.getElementById("Body" + i)) {
        xmlBodyN = xmlDoc.getElementsByTagName("Body")[i];
        if (xmlBodyN) {
            d.innerHTML = xmlBodyN.childNodes[0].nodeValue;
            xmlCreate = xmlDoc.getElementsByTagName("Created")[i];
            if (!xmlCreate) continue;
            newCreate = document.createElement('span');
            newCreate.id = "Timestamp" + (i++);
            d.parent.insertBefore(newCreate, d);
    
            xmlCreate = xmlCreate.childNodes[0].nodeValue;
            jsDate = new Date(xmlCreate);
            jsDate = jsDate.format('mmmm dxx, h:nnap');
            newCreate.innerHTML = jsDate;
        } else {
            break;
        }
    }
    but if this code makes no sense, and/or you are unable to incorporate it, then you may need to employ someone to do this for you.

    Change "Timestamp" to "Created" if you want the new spans named "Created0", "Created1", etc..
    Last edited by AndrewGSW; 12-13-2012 at 05:51 PM. Reason: d
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #9
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    .. but you are not waiting for the ajax-request to complete:

    Code:
    xmlhttp.open("GET","secretlink=xml",false);
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;
    ..so none of this may work anyway!?

    Code:
    xmlhttp.onreadystatechange = processXML;
    xmlhttp.open("GET","secretlink=xml",false);
    xmlhttp.send();
    
    function processXML() {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            var i = 0, d, xmlBodyN, xmlCreate, newCreate, jsDate;
            xmlDoc = xmlhttp.responseXML;
            while (d = document.getElementById("Body" + i)) {
                xmlBodyN = xmlDoc.getElementsByTagName("Body")[i];
                if (xmlBodyN) {
                    d.innerHTML = xmlBodyN.childNodes[0].nodeValue;
                    xmlCreate = xmlDoc.getElementsByTagName("Created")[i];
                    if (!xmlCreate) continue;
                    newCreate = document.createElement('span');
                    newCreate.id = "Timestamp" + i++;
                    d.parent.insertBefore(newCreate, d);
    
                    xmlCreate = xmlCreate.childNodes[0].nodeValue;
                    jsDate = new Date(xmlCreate);
                    jsDate = jsDate.format('mmmm dxx, h:nnap');
                    newCreate.innerHTML = jsDate;
                } else {
                    break;
                }
            }
        } else {
            // Doh! Couldn't get data..
        }
    }
    Last edited by AndrewGSW; 12-13-2012 at 06:11 PM.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #10
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Or, cross-browser attempt (using firstChild.data):

    Code:
    xmlhttp.onreadystatechange = processXML;
    xmlhttp.open("GET","secretlink=xml",false);
    xmlhttp.send();
    
    function processXML() {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            var i = 0, d, xmlBodyN, xmlCreate, newCreate, jsDate;
            xmlDoc = xmlhttp.responseXML;
            while (d = document.getElementById("Body" + i)) {
                xmlBodyN = xmlDoc.getElementsByTagName("Body")[i];
                if (xmlBodyN) {
                    d.innerHTML = xmlBodyN.childNodes[0].nodeValue || 
                        xmlBodyN.firstChild.data;
                    xmlCreate = xmlDoc.getElementsByTagName("Created")[i];
                    if (!xmlCreate) continue;
                    newCreate = document.createElement('span');
                    newCreate.id = "Timestamp" + i++;
                    d.parent.insertBefore(newCreate, d);
    
                    xmlCreate = xmlCreate.childNodes[0].nodeValue || 
                        xmlBodyN.firstChild.data;
                    jsDate = new Date(xmlCreate);
                    jsDate = jsDate.format('mmmm dxx, h:nnap');
                    newCreate.innerHTML = jsDate;
                } else {
                    break;
                }
            }
        } else {
            // Doh! Couldn't get data..
        }
    }
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #11
    New Coder
    Join Date
    Dec 2012
    Posts
    15
    Thanks
    4
    Thanked 0 Times in 0 Posts
    I see what you're saying. Let me try some creative magic and see what I can come up with

    I'm sorry if it seems as if I'm trying to get you to do the work for me. Your help is sincerely appreciated and I believe I see where the problem lies.

    I will play around with it a bit and be sure to return the results as a reply! Yet again, MUCH appreciation.

    (FYI, I'm using Notepad to write all of this - much of the reason debugging and minor errors exist :/ Going to get FireBug installed ASAP to help further.)

  • #12
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    I would recommend Notepad++ or Komodo Edit; Komodo will indicate errors without any configuring (screenshot attached). (Firebug is not an editor.)
    Attached Thumbnails Attached Thumbnails Auto-Editing XML Node Value - Make timestamp readable-komodo2.jpg  
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •