2

I would like to make a column that shows how old a list item is. Since the calculated value [Today] isn't supported I need to come up with another way to subtract date created with the current date.

To reiterate I need a column that always shows the current date as days go on.

I figured I would make a script that would always give the current day:

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; 
var yyyy = today.getFullYear();

if(dd<10) {
    dd='0'+dd
} 

if(mm<10) {
    mm='0'+mm
} 

today = mm+'/'+dd+'/'+yyyy;
document.write(today);
//document.querySelector(".class").innerHTML = (today);
//document.getElementById("id").innerHTML = (today);

Now I figured it sure would be easy to just use the .innerHTML with a corresponding id but I only have classes to work with. Again the class structure isn't specific enough to just insert my today's date into its cell.

So I'm really stuck guys and my SharePoint developing experience is hitting a wall.

Idea:

So I've used SP services in the past and thought that maybe it's UpdateListItems operation might help. Primarily this example:

$(document).ready(function() {
    $("#feedback-submit input").click(function() {

        var subject = $("#feedback-subject-input input").val();
        var message = $("#feedback-message-input textarea").text();

        CreateNewItem(subject, message);        

    });
});

function CreateNewItem(subject, message) {
    $().SPServices({
        operation: "UpdateListItems",
        async: false,
        batchCmd: "New",
        listName: "Feedback",
        valuepairs: [["Title", subject], ["Message", message]],
        completefunc: function(xData, Status) {
          alert("completed");
        }
    });
}

I was thinking if this was able to create a list item it could be able to add my current date javascript to it when the item is created. But again my ability to manipulate code this advanced is out of my ability.

Again any help would be appreciated.

Code Review:

Alright so I took a shot at creating a mock up of what I think might work. I haven't tested it because I am unsure if this is even legal in regards to syntax and structure.

$(document).ready(function() {
    $("no_idea_what_to_put_here").click(function() {

        var date = $("no_idea_what_to_put_here").val();

        CreateNewItem(date);        
    });


    $(document).ready(function CreateNewItem(date) {
        $().SPServices({
            operation: "UpdateListItems",
            async: false,
            batchCmd: "New",
            listName: "LISTNAME",
            valuepairs: [document.write(today), date],
            completefunc: function(xData, Status) {
              alert("completed");
            }
        });
    });
    $(document).ready(function() {
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; 
        var yyyy = today.getFullYear();

        if(dd<10) {
            dd='0'+dd
        } 

        if(mm<10) {
            mm='0'+mm
        } 

        today = mm+'/'+dd+'/'+yyyy;
    });
});
  • Which version of SharePoint? You can use client side rendering if you're using 2013; you can customize a list view in SP Designer on 2007 or later – John-M Aug 28 '14 at 3:39
  • Oh shoot I forgot to mention which version. This is SharePoint 2013 Online. Would client side rendering be able to accomplish what I'm trying to do? – Lincoln Hach Yellick Aug 28 '14 at 14:17
2

Edit: on MDS...

If you would like to continue to use the Minimal Download Strategy (MDS) and client-side rendering with JSlink you'll need to modify the solution below; please see my answer to a similar question here for more information: Client-side rendering (JS Link) status changes in sharepoint list


I figured out how to do this using client side rendering with JSLink so figured I would post here:

All I'm doing is taking the existing Modified field and rendering it in a different way, so there is no stored value for how old the item is anywhere on SharePoint -- it's calculated at load-time by the client.

First you'll need a js file somewhere a user viewing your page would have access to -- I used a regular old Asset Library since my environment is also on SharePoint Online.

Here is the script I came up with, this should work for any views that have the standard 'Modified' field. Here is the js file in its entirety:

'use strict';
(function() {
    // the name for this object doesn't matter
    var timeSinceFieldViewCtx = {};
    // just use the Templates and Templates.Fields convention below
    timeSinceFieldViewCtx.Templates = {};
    timeSinceFieldViewCtx.Templates.Fields = {
        // Each key value in this object should be the field name
        // so spelling and case matter and should match your list
        "Modified": {
            /* Each key here should be the view/form you want to use
               this custom rendering, choices include: 'View', 'DisplayForm',
               'EditForm', 'NewForm'. The value should point to the function 
               that will actually perform the rendering, which we will define 
               below -- outside of this IIFE. */ 
            "View": timeSinceFieldViewTemplate
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(timeSinceFieldViewCtx);
})();

function timeSinceFieldViewTemplate(ctx) {
    // you access the current list item properties with ctx.CurrentItem
    var dateDiff = new Date() - new Date(ctx.CurrentItem.Modified);
    var daysDiff = Math.floor(dateDiff / 1000 / 60 / 60 / 24);
    return daysDiff + " Days Ago";
}

Save the file, and copy a link to it.

Go to the list view that you want to apply this rendering to; edit the page (you may need to look in the dropdown under the gear); edit the list view web part. Under 'Miscellaneous' you'll see the "JS Link" property.

Something that I got caught up on, is that you can't just use a normal URL here as the link property, you have to use a URL token like the ones listed here. Like I said earlier, I put my file in the Assets Library, and I called it jsLinkTest.js so my JS Link value was:

~site/SiteAssets/jsLinkTest.js

You can modify the timeSinceFieldViewTemplate function to provide more precise or robust values ("1 Day" vs "1 Days", or converting to "Minutes" or "Hours" if the time is less than a day, etc.) -- and you can modify the field from 'Modified' to some other field if you need.

Here are the links I used to work through this:

  • Mods: Let this one pass, but John-o you magnificent bastard. I dub thee the John-o solution! Thanks. I mean it. This will be a great solution for anyone who finds this. – Lincoln Hach Yellick Sep 5 '14 at 14:40
  • Glad you find it useful! – John-M Sep 5 '14 at 14:48
  • Have a Look at momen.js too.That Produce User friedly Outputs also. – Sascha Nov 14 '14 at 20:03
0

For new/edit form's, the inputs all have titles that are set to the field name. So if your field is called "Today", then the following jQuery selector will retrieve the field:

$("input[title='Today']"); // If the field is a required field, then it will be title='Today Required Field'

Then use .val(today) to set the inputs value. But this only helps you when adding/editing the list item. If a user opens the display form or views it in a list view web part, and the item has not been created/edited that day, then it will not be accurate. You will need another solution. Perhaps a simple javascript function that reads the value of the created date, and calculates the difference from today's date. This can be done with jslinks, or a content editor web part on the page.

  • I just update my post and add a mock up of what I thought how it might work. Mind taking a look at the bottom most block of code? – Lincoln Hach Yellick Aug 28 '14 at 17:16
0

If you need to only show and not save it, you don't need ajax, you can find the creation date on the bottom :

$("table:contains('Created')").text() Then, you just split it : var res = str.split(" "); and get the date:

var date11 = res[3].split('/');

Then you just write there the difference.

  • Well in a sense it will be saved. It will update as the days go by once you submit the new item with the date cell attached to my function. Again i'm not sure if this is possible. I'm just connecting theories of what spservices can do. – Lincoln Hach Yellick Aug 29 '14 at 16:48
  • Ask yrself if you really need to save it - for ex. to sort how many days is overdue .The problem with saving is when to do it? Every time you see the list item? Once per day at night? I would suggest making a console application and update the values every night. Simple, efficient and no overhead. – XristosK Aug 29 '14 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.